﻿var map, layerE, layerC, layerMarkers;
var vectorLayer_blue, vectorLayer_red, vectorLayer_green, vectorLayer_dir, vectorLayer_stop;
var lineFeature_blue, lineFeature_red, lineFeature_green, MarkerFeature_dir,MarkerFeature_dir2,MarkerFeature_dir3,MarkerFeature_dir4, lineFeature_stop;  //openlayers
var isShowPath = false;
var selectControl;
var markerStar, markerStart, markerEnd; //marker
var styleStar, styleStart, styleEnd;        //marker style
var doAction = 'doPan';
var tempLon, tempLat;
var fromLon, fromLat, toLon, toLat; //for real point (routing analys)
var fromLon_, fromLat_, toLon_, toLat_; //for display point (show icon)
var tempName, fromName, toName;
var swapFlag = 0; //make sure both "from" and "to" are completed

var gFromName = [];
var gFromLon = [];
var gFromLat = [];
var gFromInt = 0;

var gToName = [];
var gToLon = [];
var gToLat = [];
var gToInt = 0;

var gCaName = [];
var gCaLon = [];
var gCaLat = [];
var gCaInt = 0;

var gTaName = [];
var gTaLon = [];
var gTaLat = [];
var gTaInt = 0;

var gSkipMarker = [];
var gSkipLon = [];
var gSkipLat = [];
var gSkipNode = [];
var gSkipInt = 0;

var gIncludeMarker = [];
var gIncludeLon = [];
var gIncludeLat = [];
var gIncludeInt = 0;

var gAllNode = [];
var gAllEdge = [];
var gAllEdgeLength = [];

var currentTabID = 1; //default is "Route Search"
var TabHtml_1;
var TabHtml_2;
var TabHtml_3;
var gBack;

//supermap
var smMap = null;
//var smMap1 = null;
//var smMap2 = null;
//var smMap3 = null;
//var smMap4 = null;
var smEdges;
var strCoords='';
var strPathInfo='';

var w_height;
var w_width;
    
var map_point_test = "zoom" + "," + "bound_left" + "," + "bound_top" + "," + "res" + "," + "tileSizeW"+ "," + "tileSizeH" + "\n";

var uat_map_left = 0;
var uat_map_right = 0;
var uat_map_top = 0;
var uat_map_bottom = 0;
var uat_map_url = "";

var uat_image_top_style = null;
var uat_image_down_style = null;

var uat_top_marker = null;
var uat_down_marker = null;

var time1;
var time2;
var time3;
var time4;
var time5;
var time6;
var time7;
var time8;
var time9;
var time10;
var time11;
var time12;
var time13;
var time14;
var time15;
var time16;


function clearTimeVariable(){

    time1=null;
     time2=null;
     time3=null;
     time4=null;
     time5=null;
     time6=null;
     time7=null;
     time8=null;
     time9=null;
     time10=null;
     time11=null;
     time12=null;
     time13=null;
     time14=null;
     time15=null;
     time16=null;

}


function onPopupClose(evt) { selectControl.unselect(selectedFeature);}

function onFeatureSelect(feature) { 



    var isOther = false;    
    selectedFeature = feature;
    var strPop = '<b>' + dispNonStopping[langMod] + ': </b>';
    strPop = strPop + dispVEHICLE_TY_line[langMod][feature.attributes.VEHICLE_TY] + '<br /><b>' + dispVehicleType[langMod] + ': </b>' + dispVEHICLE_TY[langMod][feature.attributes.VEHICLE_TY];
    if (feature.attributes.VEHICLE_TY == 5){
        isOther = true;
    }
//  if (feature.attributes.VEHICLE_TY == 1){
//      strPop = strPop + 'Blue Line<br /><b>Vehicle Type: </b>All motor vehicles';
//  }else if (feature.attributes.VEHICLE_TY == 2){
//      strPop = strPop + 'Green Line<br /><b>Vehicle Type: </b>Taxis';
//  }else if (feature.attributes.VEHICLE_TY == 3){
//      strPop = strPop + 'Red Line<br /><b>Vehicle Type: </b>PLBs';
//  }else if (feature.attributes.VEHICLE_TY == 4){
//      strPop = strPop + 'Yellow Line<br /><b>Vehicle Type: </b>Goods Vehicles';
//  }else if (feature.attributes.VEHICLE_TY == 5){
//      strPop = strPop + 'Cyan Line<br /><b>Vehicle Type: </b>Please see remarks below';
//      isOther = true;
//  }else{
//      strPop = strPop + 'Other Line<br /><b>Vehicle Type: </b>Unknow ';
//      isOther = true;
//  }
    strPop=strPop + '<br /><b>' + dispTimeZone[langMod] + ': </b>';
    strPop = strPop + dispTIME_ZONE[langMod][feature.attributes.TIME_ZONE];
    if (feature.attributes.TIME_ZONE == 5){
        isOther = true;
    }
//  if (feature.attributes.TIME_ZONE == 1){
//      strPop = strPop + '24 Hours';
//  }else if (feature.attributes.TIME_ZONE == 2){
//      strPop = strPop + '8 am to 10 am and 5 pm to 7 pm';
//  }else if (feature.attributes.TIME_ZONE == 3){
//      strPop = strPop + '7 am to 7 pm';
//  }else if (feature.attributes.TIME_ZONE == 4){
//      strPop = strPop + '7 am to midnight';
//  }else if (feature.attributes.TIME_ZONE == 5){
//      strPop = strPop + 'Please see remarks below';
//      isOther = true;
//  }else{
//      strPop = strPop + 'Unknow ';
//      isOther = true;
//  }
    strPop=strPop + '<br /><b>' + dispEffectiveDay[langMod] + ': </b>';
    strPop = strPop + dispEFFECTIVE[langMod][feature.attributes.EFFECTIVE_];
    if (feature.attributes.EFFECTIVE_ == 4){
        isOther = true;
    }
    
//  if (feature.attributes.EFFECTIVE_ == 1){
//      strPop = strPop + 'All days';
//  }else if (feature.attributes.EFFECTIVE_ == 2){
//      strPop = strPop + 'All days except Sundays and Public Holidays';
//  }else if (feature.attributes.EFFECTIVE_ == 3){
//      strPop = strPop + 'General Holidays (Sundays and Public Holidays)';
//  }else if (feature.attributes.EFFECTIVE_ == 4){
//      strPop = strPop + 'Please see remarks below';
//  }else{
//      strPop = strPop + 'Unknow';
//      isOther = true;
//  }
    if (isOther == true){
        //strPop=strPop + '<br /><b>Remarks: </b>' + feature.attributes.REMARKS;
        strPop=strPop + '<br /><b>' + dispRemarks[langMod] + ': </b>' + feature.attributes.REMARKS;     
    }
    popup = new OpenLayers.Popup.FramedCloud("chicken", 
        feature.geometry.getBounds().getCenterLonLat(),
        null,
        "<div style='font-size:.8em'>" + strPop +"</div>",
        null, true, onPopupClose);
    feature.popup = popup;
    map.addPopup(popup);
}

function onFeatureUnselect(feature) {
    map.removePopup(feature.popup);
    feature.popup.destroy();
    feature.popup = null;
}    

function map_init(location, zoom){
    //alert ("do it");

    OpenLayers.IMAGE_RELOAD_ATTEMPTS = 3;
    map = new OpenLayers.Map( 'map', {
        maxExtent: new OpenLayers.Bounds(-20037508.3427892,-20037508.3427892,20037508.3427892,20037508.3427892), 
        numZoomLevels:20, 
        maxResolution:156543.0339, 
        units:'m', 
        projection: "EPSG:900913",
        displayProjection: new OpenLayers.Projection("EPSG:4326"), 
        controls: [  
        new OpenLayers.Control.Navigation(), 
        new OpenLayers.Control.NorthArrow(),
        new OpenLayers.Control.ScaleLine({position: new OpenLayers.Pixel(560,380)})

        ]
    });
    layerE = new OpenLayers.Layer.TMS( "OpenStreetMap", 
        //["http://203.194.149.169/development_map/map/20110503/eng/"],
        //["http://203.194.149.168/drss/map/20110503/eng/"],
        //["http://203.194.149.169/drss/map/eng-20110511/"],
        //["http://203.194.149.169/drss/map/eng/"],
        //["http://203.194.149.168/drss/rao/2012en/"],
        //["http://203.194.149.169/drss/map/rao/2013en/"],
        //["http://203.194.149.169/drss/map/rao/2013en/"],
        ["http://203.194.149.168/drss_maploc/rao/201307en/"],           
        {layername: 'Counties', buffer: 1,'sphericalMercator': true, getURL: function (bounds) 
            {
                // alert(bounds.left + ',' + bounds.top)
                var z = this.map.getZoom();
                var url = this.url;
                var path = 'blank.png' ;
                //if ( z <= 9 && z >= 5 )
                //{
                var res = this.map.getResolution();
                var x = Math.round((bounds.left - this.maxExtent.left) / (res * this.tileSize.w));
                var y = Math.round((this.maxExtent.top - bounds.top) / (res * this.tileSize.h));
                var limit = Math.pow(2, z);
                var m = x%10;
                var n = y%10;
                var path = m + "" + n + "/" + z + "_" + x + "_" + y + ".png";   //z + "/x" + x + "_y" + y + ".png";
                //alert (path);
                //}


                map_point_test += z + "," + bounds.left + "," + bounds.top + "," + res + "," + this.tileSize.w + "," + this.tileSize.h + "," + this.maxExtent.left + "," + this.maxExtent.top + "\n";


                if(uat_map_left == 0 || uat_map_left > bounds.left){
                    uat_map_left = bounds.left;
                }
                
                if(uat_map_right == 0 || uat_map_right < bounds.right){
                    uat_map_right = bounds.right;
                    //alert(uat_map_right);
                }
                
                if(uat_map_top == 0 || uat_map_top > bounds.top){
                    uat_map_top = bounds.top;
                }
                
                if(uat_map_bottom == 0 || uat_map_bottom < bounds.bottom){
                    uat_map_bottom = bounds.bottom;
                    //alert(uat_map_bottom);
                }
                
                








                if (url instanceof Array)
                {
                    //alert ("ok");
                    url = this.selectUrl(path, url);
                    //alert (url);
                }
                //alert ( url + path);
                
                uat_map_url +=  url + path + '\n';
                
                return url + path;
                
            }
        } 
    );
    layerC = new OpenLayers.Layer.TMS( "OpenStreetMap", 
        //["http://203.194.149.169/development_map/map/20110503/chi/"],
        //["http://203.194.149.168/drss/map/20110503/chi/"],
        //["http://203.194.149.169/drss/map/chi-20110511/"],
        //["http://203.194.149.169/drss/map/chi/"],
        //["http://203.194.149.168/drss/rao/2012cn/"],
        //["http://203.194.149.169/drss/map/rao/2013cn/"],
        //["http://203.194.149.169/drss/map/rao/2013cn/"],
        ["http://203.194.149.168/drss_maploc/rao/201307cn/"],
        {layername: 'Counties', buffer: 1,'sphericalMercator': true, getURL: function (bounds) 
            {
                var z = this.map.getZoom();
                var url = this.url;
                var path = 'blank.png' ;
                //if ( z <= 9 && z >= 5 )
                //{
                var res = this.map.getResolution();
                var x = Math.round((bounds.left - this.maxExtent.left) / (res * this.tileSize.w));
                var y = Math.round((this.maxExtent.top - bounds.top) / (res * this.tileSize.h));
                var limit = Math.pow(2, z);
                var m = x%10;
                var n = y%10;
                var path = m + "" + n + "/" + z + "_" + x + "_" + y + ".png";   //z + "/x" + x + "_y" + y + ".png";
                //alert (path);
                //}















                if (url instanceof Array)
                {
                    //alert ("ok");
                    url = this.selectUrl(path, url);
                    //alert (url);
                }
                //alert ( url + path);
                return url + path;
                
            }
        } 
    );
    //setBaseLayer
    //setVisibility
    //display
    //alert (lang);
    map.addLayer(layerE);
    map.addLayer(layerC);
    if (lang == "E"){
        map.setBaseLayer(layerE);
        map.addControl(new OpenLayers.Control.LandsD_e());
    }else{
        map.setBaseLayer(layerC);
        map.addControl(new OpenLayers.Control.LandsD_c());
    }
    //blue line
    var layer_style = OpenLayers.Util.extend({}, OpenLayers.Feature.Vector.style['default']);
    layer_style.fillOpacity = 0.2;
    layer_style.graphicOpacity = 1;
  var style_blue = OpenLayers.Util.extend({}, OpenLayers.Feature.Vector.style['default']);
  style_blue.fillOpacity = 0.2;
  style_blue.graphicOpacity = 0.5;
  style_blue.strokeColor = "blue";
  style_blue.fillColor = "blue";
  style_blue.graphicName = "star";
  style_blue.pointRadius = 10;
  style_blue.strokeWidth = 3;
  style_blue.strokeLinecap = "butt";
  var style_green = OpenLayers.Util.extend({}, OpenLayers.Feature.Vector.style['default']);
  style_green.fillOpacity = 0.2;
  style_green.graphicOpacity = 0.5;
  style_green.strokeColor = "#804000";
  style_green.fillColor = "#804000";
  style_green.graphicName = "star";
  style_green.pointRadius = 10;
  style_green.strokeWidth = 3;
  style_green.strokeLinecap = "butt";
  var style_red = OpenLayers.Util.extend({}, OpenLayers.Feature.Vector.style['default']);
  style_red.fillOpacity = 0.2;
  style_red.graphicOpacity = 0.5;
  style_red.strokeColor = "red";
  style_red.fillColor = "red";
  style_red.graphicName = "star";
  style_red.pointRadius = 10;
  style_red.strokeWidth = 4;
  style_red.strokeLinecap = "butt";
  var style_stop = OpenLayers.Util.extend({}, OpenLayers.Feature.Vector.style['default']);
  style_stop.fillOpacity = 0.2;
  style_stop.graphicOpacity = 0.5;
  style_stop.strokeColor = "green";
  style_stop.fillColor = "green";
  style_stop.graphicName = "star";
  style_stop.pointRadius = 10;
  style_stop.strokeWidth = 2;
  style_stop.strokeLinecap = "butt";
  var styleMap_stop = new OpenLayers.StyleMap({
        fillOpacity: 0.2,
        graphicOpacity: 0.5,
        fillColor: "green",
        graphicName: "star",
        pointRadius: 10,
        strokeWidth: 2,
        strokeLinecap: "butt"
    });
    var lookup = {
        1: {strokeColor: "red"},
        2: {strokeColor: "green"},
        3: {strokeColor: "gray"},
        4: {strokeColor: "yellow"},
        5: {strokeColor: "#3BDEFF"}
    }
    styleMap_stop.addUniqueValueRules("default", "VEHICLE_TY", lookup);
    

  var style_dir = new OpenLayers.StyleMap({"default": 
                            {externalGraphic: "http://203.194.149.169/drss/mapfiles/dir_0.png",
                                //graphicWidth: 17,
                                graphicHeight: 20,
                                //graphicXOffset: -10,
                                graphicYOffset: -19,
                                //rotation: "${angle}",
                                rotation: "${angle}",
                  fillOpacity: 0.8}
               });
               
  styleStar = OpenLayers.Util.extend({}, OpenLayers.Feature.Vector.style['default']);
    styleStar.graphicWidth = 21;
    styleStar.graphicHeight = 21;
    styleStar.externalGraphic = "http://203.194.149.169/drss/images/star_icons20.gif";
    styleStar.fillOpacity=1;
    styleStart = OpenLayers.Util.extend({}, OpenLayers.Feature.Vector.style['default']);
    styleStart.graphicWidth = 21;
    styleStart.graphicHeight = 21;
    styleStart.externalGraphic = "http://203.194.149.169/drss/images/flag_a.gif";
    styleStart.fillOpacity=1;
    styleEnd = OpenLayers.Util.extend({}, OpenLayers.Feature.Vector.style['default']);
    styleEnd.graphicWidth = 21;
    styleEnd.graphicHeight = 21;
    styleEnd.externalGraphic = "http://203.194.149.169/drss/images/flag_b.gif";
    styleEnd.fillOpacity=1;
         
    uat_image_top_style = OpenLayers.Util.extend({}, OpenLayers.Feature.Vector.style['default']);
    uat_image_top_style.graphicWidth = 12;
    uat_image_top_style.graphicHeight = 12;
    uat_image_top_style.externalGraphic = "http://203.194.149.169/drss/images/QuickPan_D.gif";
    uat_image_top_style.fillOpacity=1;
        
    uat_image_down_style = OpenLayers.Util.extend({}, OpenLayers.Feature.Vector.style['default']);
    uat_image_down_style.graphicWidth = 12;
    uat_image_down_style.graphicHeight = 12;
    uat_image_down_style.externalGraphic = "http://203.194.149.169/drss/images/QuickPan_U.gif";
    uat_image_down_style.fillOpacity=1;
    
  vectorLayer_blue = new OpenLayers.Layer.Vector("blueLine", {style: style_blue});
    map.addLayer(vectorLayer_blue);
    map.setLayerIndex(vectorLayer_blue,3);
    
    vectorLayer_green = new OpenLayers.Layer.Vector("greenLine", {style: style_green});
    map.addLayer(vectorLayer_green);
    map.setLayerIndex(vectorLayer_green,4);
    
    vectorLayer_red = new OpenLayers.Layer.Vector("redLine", {style: style_red});
    map.addLayer(vectorLayer_red);
    map.setLayerIndex(vectorLayer_red,5);

    
    
    vectorLayer_dir = new OpenLayers.Layer.Vector("dirMarker", {styleMap: style_dir});
    map.addLayer(vectorLayer_dir);
    map.setLayerIndex(vectorLayer_dir,6);

    layerMarkers = new OpenLayers.Layer.Vector("Markers");
    map.addLayer(layerMarkers);
    map.setLayerIndex(layerMarkers, 7);

    
    //marker
    dragControl = new OpenLayers.Control.DragFeature(layerMarkers, {'onComplete': function(feature, pixel) { 
        var lonlat = map.getLonLatFromPixel(pixel);
        //alert("Lat: " + lonlat.lat + " (Pixel.x:" + pixel.x + ")" + "\n" + "Lon: " + lonlat.lon + " (Pixel.y:" + pixel.y + ")" );
        lonlat.transform(map.getProjectionObject(),map.displayProjection);  
        //alert("Lat: " + lonlat.lat + " (Pixel.x:" + pixel.x + ")" + "\n" + "Lon: " + lonlat.lon + " (Pixel.y:" + pixel.y + ")" );
        if(feature){
            if (feature.style.externalGraphic=="http://203.194.149.169/drss/images/flag_a.gif"){
                fromLon=lonlat.lon.toFixed(6);
                fromLat=lonlat.lat.toFixed(6);
                fromLon_=lonlat.lon.toFixed(6);
                fromLat_=lonlat.lat.toFixed(6);
                doAction="doStart";
                findRoadName(lonlat.lon, lonlat.lat,"doStart");
            }else if(feature.style.externalGraphic=="http://203.194.149.169/drss/images/flag_b.gif"){
                toLon=lonlat.lon.toFixed(6);
                toLat=lonlat.lat.toFixed(6);
                toLon_=lonlat.lon.toFixed(6);
                toLat_=lonlat.lat.toFixed(6);
                doAction="doEnd";
                findRoadName(lonlat.lon, lonlat.lat,"doEnd");
            }else if(feature.style.externalGraphic=="http://203.194.149.169/drss/images/flag_c.gif"){
                if(feature.style.label=="1"){
                    gSkipLon[0] = lonlat.lon;
                    gSkipLat[0] = lonlat.lat;
                }else if (feature.style.label=="2"){
                    gSkipLon[1] = lonlat.lon;
                    gSkipLat[1] = lonlat.lat;
                }  
            }else if(feature.style.externalGraphic=="http://203.194.149.169/drss/images/flag_d.gif"){
                if(feature.style.label=="1"){
                    gIncludeLon[0] = lonlat.lon;
                    gIncludeLat[0] = lonlat.lat;
                }else if (feature.style.label=="2"){
                    gIncludeLon[1] = lonlat.lon;
                    gIncludeLat[1] = lonlat.lat;
                }
            }
        }
    }})
    
  map.addControl(dragControl);
    dragControl.activate();


//  var lonLat = new OpenLayers.LonLat(114.17939, 22.35478) ;
var lonLat = new OpenLayers.LonLat(114.1201861328375, 22.34969957381774) ;



    lonLat.transform(map.displayProjection,map.getProjectionObject());




    map.setCenter(lonLat, 11);
    map.events.register("zoomend", map, function(e) {
        // Henry
        if (map.getZoom()<11)
        {
            map.zoomTo(11); 
        }
        // Henry
        setZoomImg(map.getZoom());
        if (map.getZoom()==19){
            if (!vectorLayer_stop){
                //vectorLayer_stop = new OpenLayers.Layer.Vector("stopLine", {style: style_stop});
                vectorLayer_stop = new OpenLayers.Layer.Vector("stopLine", {styleMap: styleMap_stop});
                map.addLayer(vectorLayer_stop);
                map.setLayerIndex(vectorLayer_stop,8);






                selectControl = new OpenLayers.Control.SelectFeature(vectorLayer_stop,
                    { hover: true, onSelect: onFeatureSelect, onUnselect: onFeatureUnselect});

                map.addControl(selectControl);
                selectControl.activate();
            }
            showStoping();
            showLegendBtn();    
        }else{
            if (vectorLayer_stop){
                clearStoping(); 
                map.removeControl(selectControl);
                map.removeLayer(vectorLayer_stop);
                vectorLayer_stop = null;
            }
            hideLegendBtn();
        }
        if (isShowPath){
            vectorLayer_dir.destroyFeatures();
            if (map.getZoom() > 17){
                vectorLayer_dir.addFeatures(MarkerFeature_dir);
            }else if (map.getZoom() > 15){
                vectorLayer_dir.addFeatures(MarkerFeature_dir2);
            }else if (map.getZoom() > 12){
                vectorLayer_dir.addFeatures(MarkerFeature_dir3);
            }else {
                vectorLayer_dir.addFeatures(MarkerFeature_dir4);
            }
        }
        
        // Nelson Test
        
        var uat_map_message = "";
        
        var lonLat_lefttop = new OpenLayers.LonLat(uat_map_left, uat_map_top) ;
        lonLat_lefttop.transform(map.getProjectionObject(),map.displayProjection);
        
        var lonLat_rightbottom = new OpenLayers.LonLat(uat_map_right, uat_map_bottom) ;
        lonLat_rightbottom.transform(map.getProjectionObject(),map.displayProjection);
        
        uat_map_message += "left : " + lonLat_lefttop.lon + "\n";
        uat_map_message += "right : " + lonLat_rightbottom.lon + "\n";
        uat_map_message += "top : " + lonLat_lefttop.lat + "\n";
        uat_map_message += "bottom : " + lonLat_rightbottom.lat + "\n";
        uat_map_message += "url : \n" + uat_map_url+ "\n";
        
        OpenWindowForText(uat_map_message,'m1');
        uat_map_left = 0;
        uat_map_top = 0;
        uat_map_right = 0;
        uat_map_bottom = 0;
        uat_map_url = '';
        
        //map_point_test = "zoom" + "," + "bound_left" + "," + "bound_top" + "," + "res" + "," + "tileSizeW"+ "," + "tileSizeH" + "\n";
        
    });
    map.events.register("moveend", map, function(e) {
        if (map.getZoom()==19){
            if (!vectorLayer_stop){
                vectorLayer_stop = new OpenLayers.Layer.Vector("stopLine", {style: style_stop});
                map.addLayer(vectorLayer_stop);
                map.setLayerIndex(vectorLayer_stop,8);
                selectControl = new OpenLayers.Control.SelectFeature(vectorLayer_stop,
                    { hover: true, onSelect: onFeatureSelect, onUnselect: onFeatureUnselect});
                map.addControl(selectControl);
                selectControl.activate();
            }
            clearStoping();
            showStoping();  
        }
        
        var uat_map_message = "";
        
        var lonLat_lefttop = new OpenLayers.LonLat(uat_map_left, uat_map_top) ;
        lonLat_lefttop.transform(map.getProjectionObject(),map.displayProjection);
        
        var lonLat_rightbottom = new OpenLayers.LonLat(uat_map_right, uat_map_bottom) ;
        lonLat_rightbottom.transform(map.getProjectionObject(),map.displayProjection);
        
        
        uat_map_message += "left : " + lonLat_lefttop.lon + "\n";
        uat_map_message += "right : " + lonLat_rightbottom.lon + "\n";
        uat_map_message += "top : " + lonLat_lefttop.lat + "\n";
        uat_map_message += "bottom : " + lonLat_rightbottom.lat + "\n";
        uat_map_message += "url : \n" + uat_map_url+ "\n";
        
        OpenWindowForText(uat_map_message,'m2');
        uat_map_left = 0;
        uat_map_top = 0;
        uat_map_right = 0;
        uat_map_bottom = 0;
        uat_map_url = '';
        
        
    });
    
    map.events.register("click", map, function(e){
        if (doAction=="doStart"){
            var lonLat = map.getLonLatFromViewPortPx(e.xy);
            lonLat.transform(map.getProjectionObject(),map.displayProjection);  
            
            setStartMarker(lonLat.lon, lonLat.lat, "Self-made Start Point");
            //findRoadName(lonLat.lon, lonLat.lat);
    }else if (doAction=="doEnd"){
            var lonLat = map.getLonLatFromViewPortPx(e.xy);
            lonLat.transform(map.getProjectionObject(),map.displayProjection);  
            setEndMarker(lonLat.lon, lonLat.lat, "Self-made End Point");
            //findRoadName(lonLat.lon, lonLat.lat);
    }else if(doAction=="doSkip"){
            // Henry
            if (gSkipInt==2){   // Only allow two skip points
                alert(alertAvoid1[langMod]);
                return;
            }
            var lonLat = map.getLonLatFromViewPortPx(e.xy);
            lonLat.transform(map.getProjectionObject(),map.displayProjection);  
            gSkipInt ++;
            setSkipMarker(lonLat.lon, lonLat.lat, gSkipInt);
            findNodeID(lonLat.lon, lonLat.lat);
    }else if(doAction=="doInclude"){
            // Henry
            if (gIncludeInt==2){    // Only allow two include points
                alert(alertInclude1[langMod]);
                return;
            }
            var lonLat = map.getLonLatFromViewPortPx(e.xy);
            lonLat.transform(map.getProjectionObject(),map.displayProjection);  
            gIncludeInt ++;
            setIncludeMarker(lonLat.lon, lonLat.lat, gIncludeInt);
            //findRoadName(lonLat.lon, lonLat.lat);
    }



  });
  
  var restricted_extent = new OpenLayers.Bounds(12670000,2526000,12740800,2582000);
  map.setOptions({restrictedExtent: restricted_extent});
}

function changeCSS(myCSS){
    var css=document.getElementById("css");
    var img_s=document.getElementById("size_img_s");
    var img_m=document.getElementById("size_img_m");
    var img_l=document.getElementById("size_img_l");
    
  if (myCSS=='s'){
    css.setAttribute("href","css/drss_s.css");
    img_s.src = "images/text_size_s_on.gif";
    img_m.src = "images/text_size_m.gif";
    img_l.src = "images/text_size_l.gif";
  }else if (myCSS=='m'){
    css.setAttribute("href","css/drss_m.css");
    img_s.src = "images/text_size_s.gif";
    img_m.src = "images/text_size_m_on.gif";
    img_l.src = "images/text_size_l.gif";
  }else if (myCSS=='l'){
    css.setAttribute("href","css/drss_l.css");
    img_s.src = "images/text_size_s.gif";
    img_m.src = "images/text_size_m.gif";
    img_l.src = "images/text_size_l_on.gif";
  }
  handleResize();
}

function changelang(lang){
/*  if (lang == 'E')
    {
        parent.ban.location.href='ban.php?lang=E';
    }else if (lang == 'TC')
    {
        parent.ban.location.href='ban.php?lang=TC';
    }else if (lang == 'SC')
    {
        parent.ban.location.href='ban.php?lang=SC';
    }else{
        parent.ban.location.href='ban.php?lang=E';
    }*/
}

function goBack(){
    //alert (gBack);    
    if (gBack=="do2"){
        swithTab(2);    
    }else if (gBack=="do3"){
        swithTab(3);
    }else{
        e('s3_content').innerHTML = gBack;
        TabHtml_1 = e('s3_content').innerHTML;
    }
}

var gxmlhttp;

function showRoutes(){
    //window.open('test2.htm');
    //AJAX  
    //var xmlhttp;
    var doc;
    var strXML;
    
    var divD = document.getElementById('pathDistance');
    var divT = document.getElementById('pathTime');
    var strDistance = divD.innerHTML;
    var strTime = divT.innerHTML;
    var strRoad = '';  //avoid or includ road
    
    fromName = e("from").value.replace(/&/g,"&amp;").replace(/'/g,"&apos;");
    toName = e("to").value.replace(/&/g,"&amp;").replace(/'/g,"&apos;");
    
//  var roadList = e('roadList');
//  strRoad = roadList.options[roadList.selectedIndex].text;
//  if (strRoad !=''){
//      if (e("avoidroad").checked){
//          strRoad = 'a#' + strRoad;
//      }else{
//          strRoad = 'i#' + strRoad;
//      }
//  }

    strXML = "<DRSS><attribute from='" + fromName + "' to='" + toName + "' distance='" + strDistance + "' time='" + strTime + "' road='" + strRoad + "'/>";
    strXML = strXML + "<coords>" + strCoords + "</coords><path>" + strPathInfo + "</path></DRSS>";
    //alert(strPathInfo);
    //alert (strXML);
    if (window.ActiveXObject){
        doc = new ActiveXObject("Microsoft.XMLDOM");
        doc.loadXML(strXML);
    }else {
        doc = (new DOMParser).parseFromString(strXML, "text/xml");
    }
  if (window.ActiveXObject){
  
    //alert(doc);
    
    gxmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
    if (gxmlhttp){
            gxmlhttp.onreadystatechange=function (){
                if(gxmlhttp.readyState==4){
                    if(gxmlhttp.status==200){
                        var yy=unescape(gxmlhttp.responseText);
                        //alert (yy);
                      window.open('printroute.php?lang=' + lang + '&id=' + yy);
                    }
                }
            };
            //alert(1);
            gxmlhttp.open("POST","http://203.194.149.169/drss/saveroute.php",false);
            //alert(12);
            gxmlhttp.setRequestHeader("Content-Type","application/x-www-form-urlencoded;");
            //alert(123);
            gxmlhttp.send(doc);
            //alert(1234);
      }
  }else if(typeof XMLHttpRequest != "undefined"){
        gxmlhttp=new XMLHttpRequest();
        if (gxmlhttp){
            gxmlhttp.onload=function (){
                if(gxmlhttp.readyState==4){
                    if(gxmlhttp.status==200){
                        var yy=unescape(gxmlhttp.responseText);
                      //alert (yy);
                      window.open('printroute.php?lang=' + lang + '&id=' + yy);
                    }
                }
            };
            //alert(2);
            gxmlhttp.open("POST","saveroute.php",false);
            //alert(3);
            gxmlhttp.setRequestHeader("Content-Type","application/x-www-form-urlencoded;");
            //alert(4);
            gxmlhttp.send(doc); 
            //alert(5);
      }
    }
}

function showMap(){
    //window.open('test2.htm');
    //AJAX   
    //var xmlhttp;

    var mlevel= map.getZoom();
    var mcenterP = map.getCenter();
    var mlon = mcenterP.lon;
    var mlat = mcenterP.lat;
    window.open("printmap.php?lang=" + lang + "&level=" + mlevel + "&lon=" + mlon + "&lat=" + mlat);
}

//supermap init
function smMap_init(){

    var params = new Object();
    params.mapHandler="http://203.194.149.169/drss/AjaxScripts/";  
    params.mapName="hk0"; 
    params.imageFormat="gif";  
  params.mapScales = [1 / 1000];
  params.tileSize = 256;
  params.tileCheckTime = "60";
  params.fixedView = true;
  params.buffer = 0;
  params.disableLogo = true;  
    smMap = new SuperMap.IS.MapControl($("smMap"), params);
    smMap.Init();
    
    var params4 = new Object();
    params4.mapHandler="http://203.194.149.169/drss4/AjaxScripts/";  
    params4.mapName="hk"; 
    params4.imageFormat="gif";  
  params4.mapScales = [1 / 1000];
  params4.tileSize = 256;
  params4.tileCheckTime = "60";
  params4.fixedView = true;
  params4.buffer = 0;
  params4.disableLogo = true; 
    //smMap4 = new SuperMap.IS.MapControl($("smMap4"), params4);
    //smMap4.Init();
    
    var params1 = new Object();
    params1.mapHandler="http://203.194.149.169/drss1/AjaxScripts/";  
    params1.mapName="hk1"; 
    params1.imageFormat="gif";  
  params1.mapScales = [1 / 1000];
  params1.tileSize = 256;
  params1.tileCheckTime = "60";
  params1.fixedView = true;
  params1.buffer = 0;
  params1.disableLogo = true;
    //smMap1 = new SuperMap.IS.MapControl($("smMap1"), params1);
    //smMap1.Init();
    
    var params2 = new Object();
    params2.mapHandler="http://203.194.149.169/drss2/AjaxScripts/";  
    params2.mapName="hk2"; 
    params2.imageFormat="gif";  
  params2.mapScales = [1 / 1000];
  params2.tileSize = 256;
  params2.tileCheckTime = "60";
  params2.fixedView = true;
  params2.buffer = 0;
  params2.disableLogo = true;  
    //smMap2 = new SuperMap.IS.MapControl($("smMap2"), params2);
    //smMap2.Init();
    
//  var params3 = new Object();
//  params3.mapHandler="http://203.194.149.169/drss3/AjaxScripts/";  
//  params3.mapName="hk"; 
//  params3.imageFormat="gif";  
//  params3.mapScales = [1 / 1000];
//  params3.tileSize = 256;
//  params3.tileCheckTime = "60";
//  params3.fixedView = true;
//  params3.buffer = 0;
//  params3.disableLogo = true; 
//  smMap3 = new SuperMap.IS.MapControl($("smMap3"), params3);
//  smMap3.Init();
    
    
}

function setAction(mAction){
    if (mAction=="doStart"){
        document.start.src='images/map_a_btn_1.gif';
        document.end.src='images/map_b_btn.gif';
        document.pan.src='images/map_drag_btn.gif';
        document.skip.src='images/map_c_btn.gif';
        document.include.src='images/map_d_btn.gif';
    }
    else if (mAction=="doEnd"){
        document.end.src='images/map_b_btn_1.gif';
        document.start.src='images/map_a_btn.gif';
        document.pan.src='images/map_drag_btn.gif';
        document.skip.src='images/map_c_btn.gif';
        document.include.src='images/map_d_btn.gif';
    }
    else if (mAction=="doPan"){
        document.pan.src='images/map_drag_btn_1.gif';
        document.start.src='images/map_a_btn.gif';
        document.end.src='images/map_b_btn.gif';
        document.skip.src='images/map_c_btn.gif';
        document.include.src='images/map_d_btn.gif';
    }
    else if (mAction=="doSkip"){
        document.skip.src='images/map_c_btn_1.gif';
        document.include.src='images/map_d_btn.gif';
        document.pan.src='images/map_drag_btn.gif';
        document.start.src='images/map_a_btn.gif';
        document.end.src='images/map_b_btn.gif';
    }
    else if (mAction=="doInclude"){
        document.include.src='images/map_d_btn_1.gif';
        document.skip.src='images/map_c_btn.gif';
        document.pan.src='images/map_drag_btn.gif';
        document.start.src='images/map_a_btn.gif';
        document.end.src='images/map_b_btn.gif';
    }
    
    doAction=mAction;
}
          
function setZoom(zoom){
    document.start.src='images/map_a_btn.gif';
    document.end.src='images/map_b_btn.gif';
    document.pan.src='images/map_drag_btn_1.gif';
    map.zoomTo(zoom);   
    //setZoomImg(zoom);
}

function zoomIn(){
    document.start.src='images/map_a_btn.gif';
    document.end.src='images/map_b_btn.gif';
    document.pan.src='images/map_drag_btn_1.gif';
    map.zoomIn();   
    //var zoom = map.getZoom();
    //setZoomImg(zoom);
}

function zoomOut(){
    document.start.src='images/map_a_btn.gif';
    document.end.src='images/map_b_btn.gif';
    document.pan.src='images/map_drag_btn_1.gif';

    var zoom = map.getZoom();
    if (zoom >= 12)
    {
        map.zoomOut();  
    }
}

function setZoomImg(zoom){
    for (var i = 11; i < 20; i++) {
        var levelName = "level" + i;
        var level =  e(levelName);
        if (i == zoom){
                level.src="images/map_scale_drag_btn.gif";
        }else{
            level.src="images/spacer.gif";
        }
    }
}

function showLegendBtn(){
    var legendBtn = e("legendBtn");
    legendBtn.style.display = "";
}

function hideLegendBtn(){
    var legendBtn = e("legendBtn");
    legendBtn.style.display = "none";
}

function showAvoidToolbar(){
    var avoidToolBar = e("avoidToolbar");
    avoidToolBar.style.display = "";
}

function hideAvoidToolbar(){
    var avoidToolBar = e("avoidToolbar");
    avoidToolBar.style.display = "none";
    setAction('doPan');
}

function clearStoping(){
    if (lineFeature_stop){
        lineFeature_stop.layer.renderer.clear();
        lineFeature_stop.layer.destroyFeatures();
        lineFeature_stop = null;
    }
}

function showStoping(){
    var mTop, mBottom, mLeft, mRight;
    var mBounds;
    
    mBounds = map.getExtent();
    mBounds.transform(map.getProjectionObject(),map.displayProjection); 
    mTop = mBounds.top;
    mBottom=mBounds.bottom;
    mLeft=mBounds.left;
    mRight=mBounds.right;
    
    var xmlhttp;
    var sURL;
    sURL = "http://203.194.149.169/drss/getstoping.php?top=" + mTop + "&left=" + mLeft + "&bottom=" + mBottom + "&right=" + mRight;
    if (window.ActiveXObject){
        xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
    }else if(typeof XMLHttpRequest != "undefined"){
        xmlhttp=new XMLHttpRequest();
    }
    //alert (sURL);
    if (xmlhttp){
        xmlhttp.onreadystatechange=function () {
            if(xmlhttp.readyState==4){
                if(xmlhttp.status==200){
                    if (window.ActiveXObject){
                        xml = new ActiveXObject("Microsoft.XMLDOM");
                        //alert (xmlhttp.responseText);
                        xml.loadXML(xmlhttp.responseText);
                    }else {
                    xml= (new DOMParser).parseFromString(xmlhttp.responseText, "text/xml");
                }
                var markers = xml.documentElement.getElementsByTagName("line");
                    for (var i = 0; i < markers.length; i++) {
                        // obtain the attribues of each marker
                        var pointlist = markers[i].getAttribute("pointlist");
                      var VEHICLE_TY = markers[i].getAttribute("VEHICLE_TY");
                      var TIME_ZONE = markers[i].getAttribute("TIME_ZONE");
                      var EFFECTIVE_ = markers[i].getAttribute("EFFECTIVE_");
                      var REMARKS = markers[i].getAttribute("REMARKS");
                      var pointArr = pointlist.split(",");
                      var lonlatList = new Array();
                      var lonLat;
                      var newPoint;
                      lonlatList = [];
                        for (var j=0; j<pointArr.length; j=j+2){
                            lonLat = new OpenLayers.LonLat(pointArr[j], pointArr[j +1]) ;
                            lonLat.transform(map.displayProjection,map.getProjectionObject());  
                            newPoint= new OpenLayers.Geometry.Point(lonLat.lon, lonLat.lat);
                            lonlatList.push(newPoint);
                        }
                        
                        lineFeature_stop = new OpenLayers.Feature.Vector(new OpenLayers.Geometry.LineString(lonlatList),{'VEHICLE_TY':VEHICLE_TY,'TIME_ZONE':TIME_ZONE,'EFFECTIVE_':EFFECTIVE_,'REMARKS':REMARKS});
                vectorLayer_stop.addFeatures(lineFeature_stop);
                }
                }
            }
        }
        xmlhttp.open("get",sURL);
        xmlhttp.send(null);
    }
}
    
function setStarMarker(lon, lat, label){
    var lonLat;
    if (markerStar){
        layerMarkers.removeFeatures(markerStar);
    }

    var lonLat = new OpenLayers.LonLat(lon, lat) ;
    lonLat.transform(map.displayProjection,map.getProjectionObject());  
    markerStar = new OpenLayers.Feature.Vector(new OpenLayers.Geometry.Point(lonLat.lon, lonLat.lat),null,styleStar);
    layerMarkers.addFeatures(markerStar);

    var bounds = map.getExtent();
    if (lonLat.lon < bounds.left || lonLat.lon > bounds.right || lonLat.lat > bounds.top || lonLat.lat < bounds.bottom){
        map.panTo(lonLat);
    }
    tempLon = lon;
    tempLat = lat;
    tempName = label;
}

function setUatTopMarker(lon,lat,label){

    var lonLat;
    if (uat_top_marker){
        layerMarkers.removeFeatures(uat_top_marker);
    }

    var lonLat = new OpenLayers.LonLat(lon, lat) ;
    lonLat.transform(map.displayProjection,map.getProjectionObject());  
    uat_top_marker = new OpenLayers.Feature.Vector(new OpenLayers.Geometry.Point(lonLat.lon, lonLat.lat),null,uat_image_top_style);
    layerMarkers.addFeatures(uat_top_marker);

    var bounds = map.getExtent();
    if (lonLat.lon < bounds.left || lonLat.lon > bounds.right || lonLat.lat > bounds.top || lonLat.lat < bounds.bottom){
        map.panTo(lonLat);
    }
    
}

function setUatDownMarker(lon,lat,label){

    var lonLat;
    if (uat_down_marker){
        layerMarkers.removeFeatures(uat_down_marker);
    }

    var lonLat = new OpenLayers.LonLat(lon, lat) ;
    lonLat.transform(map.displayProjection,map.getProjectionObject());  
    uat_down_marker = new OpenLayers.Feature.Vector(new OpenLayers.Geometry.Point(lonLat.lon, lonLat.lat),null,uat_image_down_style);
    layerMarkers.addFeatures(uat_down_marker);

    var bounds = map.getExtent();
    if (lonLat.lon < bounds.left || lonLat.lon > bounds.right || lonLat.lat > bounds.top || lonLat.lat < bounds.bottom){
        map.panTo(lonLat);
    }
    
}

function setStartMarker(lon, lat, label){
    var lonLat;
    fromLon = lon;
    fromLat = lat;
    fromLon_ = lon;
    fromLat_ = lat;
    fromName = label;
    if (markerStart){
        layerMarkers.removeFeatures(markerStart);
    }

    var lonLat = new OpenLayers.LonLat(lon, lat) ;
    lonLat.transform(map.displayProjection,map.getProjectionObject());  
    markerStart = new OpenLayers.Feature.Vector(new OpenLayers.Geometry.Point(lonLat.lon, lonLat.lat),null,styleStart);
    layerMarkers.addFeatures(markerStart);

    var bounds = map.getExtent();
    if (lonLat.lon < bounds.left || lonLat.lon > bounds.right || lonLat.lat > bounds.top || lonLat.lat < bounds.bottom){
        map.panTo(lonLat);
    }
    //fromLon = lon;
    //fromLat = lat;
    //fromName = label;
    if(label != "Self-made Point"){
        doAction = "doPoiStart";
    }
    
    if( label != "Self-made Start Point"){
        e("from").value = fromName;
    }
    else{
        doAction = "doStart";
    }
    
    
    
    findRoadName(lon, lat,doAction);  
}

function setEndMarker(lon, lat, label){
    var lonLat;
    toLon = lon;
    toLat = lat;
    toLon_ = lon;
    toLat_ = lat;
    toName = label;
    if (markerEnd){
        layerMarkers.removeFeatures(markerEnd);
    }

    var lonLat = new OpenLayers.LonLat(lon, lat) ;
    lonLat.transform(map.displayProjection,map.getProjectionObject());  
    markerEnd = new OpenLayers.Feature.Vector(new OpenLayers.Geometry.Point(lonLat.lon, lonLat.lat),null,styleEnd);
    layerMarkers.addFeatures(markerEnd);
    
    var bounds = map.getExtent();
    if (lonLat.lon < bounds.left || lonLat.lon > bounds.right || lonLat.lat > bounds.top || lonLat.lat < bounds.bottom){
        map.panTo(lonLat);
    }
    //toLon = lon;
    //toLat = lat;
    //toName = label;
    
    if(label != "Self-made Point"){
        doAction = "doPoiEnd";
    }
    
    if( label != "Self-made End Point"){
        e("to").value = toName;
    }
    else{
        doAction = "doEnd";
    }
    
    

    findRoadName(lon, lat, doAction);    
}

function setSkipMarker(lon, lat, label){
    var lonLat = new OpenLayers.LonLat(lon, lat) ;
    lonLat.transform(map.displayProjection,map.getProjectionObject());  
    var styleSkip = OpenLayers.Util.extend({}, OpenLayers.Feature.Vector.style['default']);
    styleSkip.graphicWidth = 21;
    styleSkip.graphicHeight = 21;
    styleSkip.externalGraphic = "http://203.194.149.169/drss/images/flag_c.gif";
    styleSkip.fillOpacity=1;
    styleSkip.label = label;
    var newMarker = new OpenLayers.Feature.Vector(new OpenLayers.Geometry.Point(lonLat.lon, lonLat.lat),null,styleSkip);
    gSkipMarker[gSkipInt-1] = newMarker;
    gSkipLon[gSkipInt-1] = lon;
    gSkipLat[gSkipInt-1] = lat;
    layerMarkers.addFeatures(gSkipMarker[gSkipInt-1]);
    
    var bounds = map.getExtent();
    if (lonLat.lon < bounds.left || lonLat.lon > bounds.right || lonLat.lat > bounds.top || lonLat.lat < bounds.bottom){
        map.panTo(lonLat);
    }
    
}

function setIncludeMarker(lon, lat, label){
    var lonLat = new OpenLayers.LonLat(lon, lat) ;
    lonLat.transform(map.displayProjection,map.getProjectionObject());  
    var styleInclude = OpenLayers.Util.extend({}, OpenLayers.Feature.Vector.style['default']);
    styleInclude.graphicWidth = 21;
    styleInclude.graphicHeight = 21;
    styleInclude.externalGraphic = "http://203.194.149.169/drss/images/flag_d.gif";
    styleInclude.fillOpacity=1;
    styleInclude.label = label;
    var newMarker = new OpenLayers.Feature.Vector(new OpenLayers.Geometry.Point(lonLat.lon, lonLat.lat),null,styleInclude);
    gIncludeMarker[gIncludeInt-1] = newMarker;
    gIncludeLon[gIncludeInt-1] = lon;
    gIncludeLat[gIncludeInt-1] = lat;
    layerMarkers.addFeatures(gIncludeMarker[gIncludeInt-1]);
    
    var msg_nelson_20130115 = 'Lat (IRN Location):' + '\n';
    msg_nelson_20130115 += lat + '\n';
    msg_nelson_20130115 += 'Lng (IRN Location):' + '\n';
    msg_nelson_20130115 += lon + '\n';
    OpenWindowForText(msg_nelson_20130115,'location_point');
    
    var bounds = map.getExtent();
    if (lonLat.lon < bounds.left || lonLat.lon > bounds.right || lonLat.lat > bounds.top || lonLat.lat < bounds.bottom){
        map.panTo(lonLat);
    }
    
}

function positionPoint(id, lon, lat){

    var lonLat;
    if (markerStar){
        layerMarkers.removeFeatures(markerStar);
    }
    if (lineFeature_red){
        lineFeature_red.layer.renderer.clear();
        lineFeature_red.layer.destroyFeatures();
        lineFeature_red = null;
    }
  lineFeature_red = new OpenLayers.Feature.Vector(new OpenLayers.Geometry.LineString(smEdges[id]));
  vectorLayer_red.addFeatures([lineFeature_red]);

  //lineFeature_green = new OpenLayers.Feature.Vector(new OpenLayers.Geometry.LineString(smEdges[id]));
                //vectorLayer_green.addFeatures([lineFeature_green]);

                
    var lonLat = new OpenLayers.LonLat(lon, lat) ;
    lonLat.transform(map.displayProjection,map.getProjectionObject());  
    markerStar = new OpenLayers.Feature.Vector(new OpenLayers.Geometry.Point(lonLat.lon, lonLat.lat),null,styleStar);
    //no marker
    //layerMarkers.addFeatures(markerStar);

    var bounds = map.getExtent();
    if (lonLat.lon < bounds.left || lonLat.lon > bounds.right || lonLat.lat > bounds.top || lonLat.lat < bounds.bottom){
        map.panTo(lonLat);
    }
}

/*
function toStartMarker(){
    if (tempLon>0 && tempLat>0){
        layerMarkers.removeFeatures(markerStar);
        setStartMarker(tempLon, tempLat,tempName);
        e("from").value = tempName;

        tempName = "";
        tempLon = 0;
        tempLat = 0;
    }
} 

function toEndMarker(){
    if (tempLon>0 && tempLat>0){
        layerMarkers.removeFeatures(markerStar);
        setEndMarker(tempLon, tempLat, tempName);
        e("to").value = tempName;

        tempName = "";
        tempLon = 0;
        tempLat = 0;
    }   
} 
 
*/
function e(id) {return document.getElementById(id);}

function myclick(){
    var code = this.parentNode.id;
    alert (gFromLon[code]); 
}

function myFun(inP){
    alert (inP);    
}

function reset(){

}


function getTimeNow(){

    var nowtime = new Date();
    return getCurrentTimeDisplay(nowtime);
}

function getCurrentTimeDisplay(timeNow){

    var now = timeNow;
    
    var _hour = (now.getHours() < 10 ? "0" + now.getHours() : "" + now.getHours());
    var _minute = (now.getMinutes() < 10 ? "0" + now.getMinutes() : "" + now.getMinutes());
    var _second = (now.getSeconds() < 10 ? "0" + now.getSeconds() : "" + now.getSeconds());
    var _millisecond = (now.getMilliseconds() < 100 ? "0" + now.getMilliseconds() : (now.getMilliseconds() < 10 ? "0" + now.getMilliseconds() : "" + now.getMilliseconds()));
    
    var result = _hour + ":" + _minute + ":" + _second + "." + _millisecond;
    
    return result;
    
}

function getSearchInfo(myFirst){


    
    
    var spType;
    var s2_div = e("s2_div");
    var s2_content = e("s2_content");
    var s4_content = e("s4_content");
    


    if (currentTabID == 2){
        gBack = "do2";
    }else if (currentTabID == 3){
        gBack = "do3";
    }
    currentTabID = 1;
    s2_div.style.display = "none";
    s2_content.innerHTML = "";
            
    var strS4= '<table width="100%" border="0" cellspacing="0" cellpadding="0">';
    strS4 = strS4 + '<tr><td height="5" width="320"><img src="images/spacer.gif" alt="" width="5" height="5" border="0"></td></tr>';
    strS4 = strS4 + genTabTitle(2, "cat_search.gif");
    strS4 = strS4 + '<tr><td height="5" width="320"><img src="images/spacer.gif" alt="" width="5" height="5" border="0"></td></tr>';
    strS4 = strS4 + genTabTitle(3, "tourism_board.gif");
    strS4 = strS4 + '<tr><td height="5" width="320"><img src="images/spacer.gif" alt="" width="5" height="5" border="0"></td></tr></table>';
    s4_content.innerHTML = strS4;
    


    
    if (fromLon > 0 && toLon > 0){
        //time1 = getTimeNow();
        /*if (e("criteria3").checked){
            init_pathResult();
            getSP0(0, "STS");       //Shortest Travel Time (Static)
            setAction('doPan');
        }else*/ 
        if (e("criteria1").checked){
            init_pathResult();
            getSP0(0, "SD");//Shortest Distance 
            setAction('doPan');
        }else if (e("criteria4").checked){
            init_pathResult();
            getSP0(0, "STR");   //Shortest Travel Time (Real Time)
            setAction('doPan');
        }else if (e("criteria2").checked){
            init_pathResult();
            getSP0(0, "CT");    //Cheapest tunnel/bridge toll
            setAction('doPan');
        }else {
            alert ("Please select Shortest Distance!");
            return; 
        }
    }else{  




        clearBar();



        getFromInfo(true);



        getToInfo(true);

    }
    TabHtml_1 = e('s3_content').innerHTML;
}

function swap(){
    var spType;
    var s2_div = e("s2_div");
    var s2_content = e("s2_content");
    var s4_content = e("s4_content");
    
    if (currentTabID == 2){
        gBack = "do2";
    }else if (currentTabID == 3){
        gBack = "do3";
    }
    currentTabID = 1;
    s2_div.style.display = "none";
    s2_content.innerHTML = "";
            
    var strS4= '<table width="100%" border="0" cellspacing="0" cellpadding="0">';
    strS4 = strS4 + '<tr><td height="5" width="320"><img src="images/spacer.gif" alt="" width="5" height="5" border="0"></td></tr>';
    strS4 = strS4 + genTabTitle(2, "cat_search.gif");
    strS4 = strS4 + '<tr><td height="5" width="320"><img src="images/spacer.gif" alt="" width="5" height="5" border="0"></td></tr>';
    strS4 = strS4 + genTabTitle(3, "tourism_board.gif");
    strS4 = strS4 + '<tr><td height="5" width="320"><img src="images/spacer.gif" alt="" width="5" height="5" border="0"></td></tr></table>';
    s4_content.innerHTML = strS4;
    
    
    if (fromLon_ > 0 && toLon_ > 0){


       
        var tempFrom;


        var lonLatStart, lonLatEnd;
        tempFrom = e("from").value;


        e("from").value = e("to").value;


        e("to").value = tempFrom;


        fromLon = toLon_;
        fromLat = toLat_;
        toLon = fromLon_;
        toLat = fromLat_;
        fromLon_ = fromLon;
        fromLat_ = fromLat;
        toLon_ = toLon;
        toLat_ = toLat;
        
        lonLatStart = new OpenLayers.LonLat(fromLon_,fromLat_);
        lonLatStart.transform(map.displayProjection,map.getProjectionObject());
        markerStart.move(lonLatStart);
        lonLatEnd = new OpenLayers.LonLat(toLon_,toLat_);
        lonLatEnd.transform(map.displayProjection,map.getProjectionObject());
        markerEnd.move(lonLatEnd);





















        clearLine();
        swapFlag = 0;
        findRoadName(fromLon,fromLat,"doSwapStart");
        findRoadName(toLon,toLat,"doSwapEnd");
    }else{  
        if (lang == 'E'){
            alert ("Please set origin and destination.");
        } else if (lang == 'TC'){
            alert ("請設定起點及終點.");
        } else if (lang == 'SC'){
            alert ("请设定起点及终点.");
        } else {
            alert ("Please set origin and destination.");
        }       
    }
    TabHtml_1 = e('s3_content').innerHTML;
}

function getFromInfo(myFirst,myQuerykey,myPage,myPages){






    //function: search info
    var page;
    var pages;
    var querykey;
    var sURL;
    
    gFromName = [];
    gFromLon = [];
    gFromLat = [];
    gFromInt = 0;
                
    if (myFirst==true){



        if(e("from").value){
            querykey=e("from").value;
            querykey=querykey.replace(/BLOCK/ig,"block");



            sURL="http://203.194.149.169/drss/getpointsall.php?lang=" + lang + "&first=true&querykey=" + encodeURIComponent(querykey);


        } else {
            return false;
        }
    } else {
        page=myPage;
        pages=myPages;
        querykey=myQuerykey;
        sURL="http://203.194.149.169/drss/getpointsall.php?lang=" + lang + "&first=false&page=" + page + "&pages=" + pages + "&querykey=" + encodeURIComponent(querykey);
        //window.open(sURL);
        //alert (sURL);
    }
    //alert (sURL);
    //clear the result list


    clearFromBar();

    
    var xmlhttp;


    if (window.ActiveXObject){

        xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
    }else if(typeof XMLHttpRequest != "undefined"){

        xmlhttp=new XMLHttpRequest();
    }

    
    if (xmlhttp){



        xmlhttp.onreadystatechange=function () {


            if(xmlhttp.readyState==4){



                if(xmlhttp.status==200){



                    if (window.ActiveXObject){

                        xml = new ActiveXObject("Microsoft.XMLDOM");
                        
                        xml.loadXML(xmlhttp.responseText);
                    }else {



                    xml= (new DOMParser).parseFromString(xmlhttp.responseText, "text/xml");
                }
//alert (xmlhttp.responseText);
                var markers = xml.documentElement.getElementsByTagName("marker");
                var para = xml.documentElement.getElementsByTagName("para");
                
                page = parseInt(para[0].getAttribute("page"));
                pages = parseInt(para[0].getAttribute("pages"));
                querykey = para[0].getAttribute("querykey");
                    querykey = querykey.replace("''","'");
                    
                    if ( markers.length>0){
                        for (var i = 0; i < markers.length; i++) {



                        // obtain the attribues of each marker
                            var lat = parseFloat(markers[i].getAttribute("lat"));
                        var lng = parseFloat(markers[i].getAttribute("lng"));
                        var label = markers[i].getAttribute("NAME");
                        
                            gFromName[gFromInt] = label;
                            gFromLon[gFromInt] = lng;
                            gFromLat[gFromInt] = lat;
                        addFromBarItem (label, gFromInt);
                        gFromInt++;
                    }

                    //pre 1,2,3 next
                    var listbar="";

                        if (page>1){

                            var linkUp='"javascript:getFromInfo(false,&quot;' + querykey + '&quot;,' + (page-1) + ',' + pages + ');"';
                            listbar +='<a href=' + linkUp + ' style="text-decoration: none; color: blue;">' + dispPre[langMod] + '</a> ';
                        }

                        listbar = listbar + '<SPAN style="text-decoration: none; color: gray;"> | </SPAN>';

                        if (page<pages){

                            var linkDown='"javascript:getFromInfo(false,&quot;' + querykey + '&quot;,' + (page+1) + ',' + pages + ');"';
                            listbar +='<a href=' + linkDown + ' style="text-decoration: none; color: blue;">' + dispNext[langMod] + '</a>&nbsp;';
                        }

                        addFromBarFoot (listbar);
                    }else{




                        var strDiv = '<table width="100%" border="0" cellpadding="0" cellspacing="0" id="tableline2">';
                        strDiv = strDiv + '<tr><td width="30" height="3" colspan="3" background="images/table_line_bg.gif"><img src="images/spacer.gif" alt="" width="1" height="3" border="0" /></td>';
                        strDiv = strDiv + '</tr><tr><td height="3" colspan="3" class="normalText"><img src="images/spacer.gif" alt="" width="1" height="3" border="0" /></td>';
                        strDiv = strDiv + '</tr></table><table width="100%" border="0" cellpadding="0" cellspacing="0" id="roadname">';
                        strDiv = strDiv + '<tr><td width="5" class="normalText"><img src="images/spacer.gif" alt="" width="5" height="1" border="0" /></td>';
                        strDiv = strDiv + '<td valign="top" align="left" class="normalText">' + dispNoRecordFound[langMod] + '</td>';
                        strDiv = strDiv + '</tr><tr><td height="3" colspan="3" class="normalText"><img src="images/spacer.gif" alt="" width="1" height="3" border="0" /></td>';
                        strDiv = strDiv + '</tr></table>';

                        //alert (strDiv);
                        var myDiv = e("divFrom_10");
                        myDiv.innerHTML = strDiv;   
                    }

                    TabHtml_1 = e('s3_content').innerHTML;
                    gBack = e('s3_content').innerHTML;


                }

            }
        }








        xmlhttp.open("get",sURL);


        xmlhttp.send(null);



    }
}

function getToInfo(myFirst,myQuerykey,myPage,myPages){
    //function: search info
    var page;
    var pages;
    var querykey;
    var sURL;
    
    gToMarkers = [];
    gToHtmls = [];
    gToPoints = [];
    gToInt = 0;
                
    if (myFirst==true){
        if(e("to").value){
            querykey=e("to").value;
            querykey=querykey.replace(/BLOCK/ig,"block");

            sURL="http://203.194.149.169/drss/getpointsall.php?lang=" + lang + "&first=true&querykey=" + encodeURIComponent(querykey);
        } else {
            return false;
        }
    } else {
        page=myPage;
        pages=myPages;
        querykey=myQuerykey;
        sURL="http://203.194.149.169/drss/getpointsall.php?lang=" + lang + "&first=false&page=" + page + "&pages=" + pages + "&querykey=" + encodeURIComponent(querykey);
        //window.open(sURL);
        //alert (sURL);
    }
    //alert (sURL);
//window.open(sURL);
    //clear the result list
    clearToBar();
    
    var xmlhttp;

    if (window.ActiveXObject){
        xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
    }else if(typeof XMLHttpRequest != "undefined"){
        xmlhttp=new XMLHttpRequest();
    }
    
    if (xmlhttp){
        xmlhttp.onreadystatechange=function () {
            if(xmlhttp.readyState==4){
                if(xmlhttp.status==200){
                    if (window.ActiveXObject){
                        xml = new ActiveXObject("Microsoft.XMLDOM");
                        xml.loadXML(xmlhttp.responseText);
                    }else {
                    xml= (new DOMParser).parseFromString(xmlhttp.responseText, "text/xml");
                }
                var markers = xml.documentElement.getElementsByTagName("marker");
                var para = xml.documentElement.getElementsByTagName("para");
                
                page = parseInt(para[0].getAttribute("page"));
                pages = parseInt(para[0].getAttribute("pages"));
                querykey = para[0].getAttribute("querykey");
                    querykey = querykey.replace("''","'");
                    if ( markers.length>0){
                        for (var i = 0; i < markers.length; i++) {
                        // obtain the attribues of each marker
                            var lat = parseFloat(markers[i].getAttribute("lat"));
                        var lng = parseFloat(markers[i].getAttribute("lng"));
                        var label = markers[i].getAttribute("NAME");

                    gToName[gToInt] = label;
                            gToLon[gToInt] = lng;
                            gToLat[gToInt] = lat;
                        addToBarItem (label,gToInt);
                        gToInt++;
                    }
                    //pre 1,2,3 next
                    var listbar="";
                        if (page>1){
                            var linkUp='"javascript:getToInfo(false,&quot;' + querykey + '&quot;,' + (page-1) + ',' + pages + ');"';
                            listbar +='<a href=' + linkUp + ' style="text-decoration: none; color: blue;">' + dispPre[langMod] + '</a> ';
                        }
                        listbar = listbar + '<SPAN style="text-decoration: none; color: gray;"> | </SPAN>';
                        if (page<pages){
                            var linkDown='"javascript:getToInfo(false,&quot;' + querykey + '&quot;,' + (page+1) + ',' + pages + ');"';
                            listbar +='<a href=' + linkDown + ' style="text-decoration: none; color: blue;">' + dispNext[langMod] + '</a>&nbsp;';
                        }
                    //alert (listbar);
                        addToBarFoot (listbar);
                    }else{
                        var strDiv = '<table width="100%" border="0" cellpadding="0" cellspacing="0" id="tableline2">';
                        strDiv = strDiv + '<tr><td width="30" height="3" colspan="3" background="images/table_line_bg.gif"><img src="images/spacer.gif" alt="" width="1" height="3" border="0" /></td>';
                        strDiv = strDiv + '</tr><tr><td height="3" colspan="3" class="normalText"><img src="images/spacer.gif" alt="" width="1" height="3" border="0" /></td>';
                        strDiv = strDiv + '</tr></table><table width="100%" border="0" cellpadding="0" cellspacing="0" id="roadname">';
                        strDiv = strDiv + '<tr><td width="5" class="normalText"><img src="images/spacer.gif" alt="" width="5" height="1" border="0" /></td>';
                        strDiv = strDiv + '<td valign="top" align="left" class="normalText">' + dispNoRecordFound[langMod] + '</td>';
                        strDiv = strDiv + '</tr><tr><td height="3" colspan="3" class="normalText"><img src="images/spacer.gif" alt="" width="1" height="3" border="0" /></td>';
                        strDiv = strDiv + '</tr></table>';
                        //alert (strDiv);
                        var myDiv = e("divTo_10");
                        myDiv.innerHTML = strDiv;   
                    }
                    TabHtml_1 = e('s3_content').innerHTML;
                    gBack = e('s3_content').innerHTML;
                }
            }
        }
        xmlhttp.open("get",sURL);
        xmlhttp.send(null);
    }
}

function getCategory(myFirst,myCate,myDist,myPage,myPages){
    //function: search info
    var page;
    var pages;
    var cate;
    var dist;
    var sURL;
    
    gCaName = [];
    gCaLon = [];
    gCaLat = [];
    gCaInt = 0;

    if (myFirst==true){
        var cateNo = e("categoryNo");
        var distNo = e("districtNo");
        cate = cateNo.options[cateNo.selectedIndex].value;
        dist = distNo.options[distNo.selectedIndex].value;
        if (cateNo!="" && dist!=""){
            sURL="http://203.194.149.169/drss/getcategory.php?lang=" + lang + "&first=true&cate=" + cate + "&dist=" + dist;
        } else {
            return false;
        }
    } else {
        page=myPage;
        pages=myPages;
        cate=myCate;
        dist=myDist;
        sURL="http://203.194.149.169/drss/getcategory.php?lang=" + lang + "&first=false&page=" + page + "&pages=" + pages + "&cate=" + cate + "&dist=" + dist;
        //alert (sURL);
    }
    //alert (sURL);
    //clear the result list
    clearCateBar();
    
    var xmlhttp;

    if (window.ActiveXObject){
        xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
    }else if(typeof XMLHttpRequest != "undefined"){
        xmlhttp=new XMLHttpRequest();
    }
    
    if (xmlhttp){
        xmlhttp.onreadystatechange=function () {
            if(xmlhttp.readyState==4){
                if(xmlhttp.status==200){
                    if (window.ActiveXObject){
                        xml = new ActiveXObject("Microsoft.XMLDOM");
                        xml.loadXML(xmlhttp.responseText);
                    }else {
                        xml= (new DOMParser).parseFromString(xmlhttp.responseText, "text/xml");
                }
                if (!xml.documentElement){
                    addCategoryItem_NULL();
                    return;
                }
                var markers = xml.documentElement.getElementsByTagName("marker");
                var para = xml.documentElement.getElementsByTagName("para");
                
                page = parseInt(para[0].getAttribute("page"));
                pages = parseInt(para[0].getAttribute("pages"));
                cate = para[0].getAttribute("cate");
                    dist = para[0].getAttribute("dist");
                    if (markers.length > 0){
                        for (var i = 0; i < markers.length; i++) {
                            // obtain the attribues of each marker
                            var lat = parseFloat(markers[i].getAttribute("lat"));
                        var lng = parseFloat(markers[i].getAttribute("lng"));
                        var label = markers[i].getAttribute("NAME");
    
                        gCaName[i] = label;
                        gCaLon[i] = lng;
                        gCaLat[i] = lat;
                            addCategoryItem (label,i);
                            gCaInt = i + 1;
                    }
                    //pre 1,2,3 next
                    var listbar="";
                        if (page>1){
                            var linkUp='"javascript:getCategory(false,&quot;' + cate + '&quot;,&quot;' + dist + '&quot;,' + (page-1) + ',' + pages + ');"';
                            listbar +='<a href=' + linkUp + ' style="text-decoration: none; color: blue;">' + dispPre[langMod] + '</a> ';
                            listbar = listbar + '<SPAN style="text-decoration: none; color: gray;"> | </SPAN>';
                        }
                        if (page<pages){
                            var linkDown='"javascript:getCategory(false,&quot;' + cate + '&quot;,&quot;' + dist + '&quot;,' + (page+1) + ',' + pages + ');"';
                            listbar +='<a href=' + linkDown + ' style="text-decoration: none; color: blue;">' + dispNext[langMod] + '</a>&nbsp;';
                        }
                        //alert (listbar);
                        addCategoryFoot (listbar);
                    }else{
                        addCategoryItem_NULL();
                    }
                    TabHtml_2 = e('s3_content').innerHTML;
                }
            }
        }
        xmlhttp.open("get",sURL);
        xmlhttp.send(null);
    }
}

function getTourism(myFirst,myDist, myId, myPage,myPages){
    //function: search info 
    var page;
    var pages;
    var dist;
    var sURL;
    
    gTaName = [];
    gTaLon = [];
    gTaLat = [];
    gTaInt = 0;

    if (myFirst==true){
        sURL="http://203.194.149.169/drss/getTourism.php?lang=" + lang + "&first=true&dist=" + myDist;
    } else {
        sURL="http://203.194.149.169/drss/getTourism.php?lang=" + lang + "&first=false&page=" + myPage + "&pages=" + myPages + "&dist=" + myDist;
    }
    //alert (sURL);
    clearTourBar(myDist);  //will do
    
    var xmlhttp;

    if (window.ActiveXObject){
        xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
    }else if(typeof XMLHttpRequest != "undefined"){
        xmlhttp=new XMLHttpRequest();
    }
    
    if (xmlhttp){
        xmlhttp.onreadystatechange=function () {
            if(xmlhttp.readyState==4){
                if(xmlhttp.status==200){
                    if (window.ActiveXObject){
                        xml = new ActiveXObject("Microsoft.XMLDOM");
                        xml.loadXML(xmlhttp.responseText);
                    }else {
                        xml= (new DOMParser).parseFromString(xmlhttp.responseText, "text/xml");
                    }
                    if (!xml.documentElement){
                        return;
                    }
                    var markers = xml.documentElement.getElementsByTagName("marker");
                    var para = xml.documentElement.getElementsByTagName("para");
                    
                    page = parseInt(para[0].getAttribute("page"));
                    pages = parseInt(para[0].getAttribute("pages"));
                        dist = para[0].getAttribute("dist");
                        
                    for (var i = 0; i < markers.length; i++) {
                        // obtain the attribues of each marker
                            var lat = parseFloat(markers[i].getAttribute("lat"));
                        var lng = parseFloat(markers[i].getAttribute("lng"));
                        var label = markers[i].getAttribute("NAME");
                            var mIndex = (myId * 10) + i;
                    var divName = "div" + myDist + "_" + i;
                    gTaName[mIndex] = label;
                            gTaLon[mIndex] = lng;
                            gTaLat[mIndex] = lat;
                        // Modified by Henry
                        // addTourItem (divName, mIndex , label, myclick);
                        addTourItem (divName, i,  label, mIndex);
                    }
                    //pre 1,2,3 next
                    var listbar="";
                        if (page>1){
                            var linkUp='"javascript:getTourism(false,&quot;' + dist + '&quot;,' + myId + ',' + (page-1) + ',' + pages + ');"';
                            listbar +='<a href=' + linkUp + ' style="text-decoration: none; color: blue;">' + dispPre[langMod] + '</a> ';
                        }
                        listbar = listbar + '<SPAN style="text-decoration: none; color: gray;"> | </SPAN>';
                        if (page<pages){
                            var linkDown='"javascript:getTourism(false,&quot;' + dist + '&quot;,' + myId + ',' + (page+1) + ',' + pages + ');"';
                            listbar +='<a href=' + linkDown + ' style="text-decoration: none; color: blue;">' + dispNext[langMod] + '</a>&nbsp;';
                        }
                    //alert (listbar);
                    addTourFoot (myDist, listbar);
                    //TabHtml_3 = e('s3_content').innerHTML;
                }
            }
        }
        xmlhttp.open("get",sURL);
        xmlhttp.send(null);
    }
}

function addFromBarItem(title, id) {
    var strDiv = '<table width="100%" border="0" cellpadding="0" cellspacing="0" id="tableline2">';
    strDiv = strDiv + '<tr><td width="30" height="3" colspan="3" background="images/table_line_bg.gif"><img src="images/spacer.gif" alt="" width="1" height="3" border="0" /></td>';
    strDiv = strDiv + '</tr><tr><td height="3" colspan="3" class="normalText"><img src="images/spacer.gif" alt="" width="1" height="3" border="0" /></td>';
    strDiv = strDiv + '</tr></table><table width="100%" border="0" cellpadding="0" cellspacing="0" id="roadname">';
    strDiv = strDiv + '<tr><td width="25" valign="top" class="normalText"><a href="#">' + (id + 1) + '.</a></td>';
    strDiv = strDiv + '<td width="5" class="normalText"><img src="images/spacer.gif" alt="" width="5" height="1" border="0" /></td>';
    strDiv = strDiv + '<td valign="top" class="normalText"><strong><a href="#" onclick="setStarMarker(' + gFromLon[id] + ',' + gFromLat[id] + ',&quot;' + gFromName[id] + '&quot;)" >' + title + '</a></strong></td>';
    strDiv = strDiv + '<td width="23" valign="top" class="normalText"><div align="right">';
    strDiv = strDiv + '<table width="100%" border="0" cellspacing="0" cellpadding="0"><tr>';
    strDiv = strDiv + '<td><a href="#" onclick="setStartMarker(' + gFromLon[id] + ',' + gFromLat[id] + ',&quot;' + gFromName[id] + '&quot;)"><img src="images/flag_a.gif" title="' + title_origin[langMod] + '" width="21" height="21" border="0" /></a></td>';
    strDiv = strDiv + '<td width="2"><img src="images/spacer.gif" alt="" width="5" height="1" border="0" /></td>';
    strDiv = strDiv + '</tr></table></div></td>';
    strDiv = strDiv + '</tr><tr><td height="3" colspan="3" class="normalText"><img src="images/spacer.gif" alt="" width="1" height="3" border="0" /></td>';
    strDiv = strDiv + '</tr></table>';
    
    var mDiv = "divFrom_" + id;
    //alert (mDiv);
    var myDiv = e(mDiv);
    myDiv.innerHTML = strDiv;
}

function addFromBarFoot(title) {
    var strDiv = '<table width="100%" border="0" cellpadding="0" cellspacing="0" id="tableline2">';
    strDiv = strDiv + '<tr><td width="30" height="3" colspan="3" background="images/table_line_bg.gif"><img src="images/spacer.gif" alt="" width="1" height="3" border="0" /></td>';
    strDiv = strDiv + '</tr><tr><td height="3" colspan="3" class="normalText"><img src="images/spacer.gif" alt="" width="1" height="3" border="0" /></td>';
    strDiv = strDiv + '</tr></table><table width="100%" border="0" cellpadding="0" cellspacing="0" id="roadname">';
    strDiv = strDiv + '<tr><td width="25" valign="top" class="normalText"><a href="#"></a></td>';
    strDiv = strDiv + '<td width="5" class="normalText"><img src="images/spacer.gif" alt="" width="5" height="1" border="0" /></td>';
    strDiv = strDiv + '<td valign="top" align="right" class="normalText">' + title + '</td>';
    strDiv = strDiv + '</tr><tr><td height="3" colspan="3" class="normalText"><img src="images/spacer.gif" alt="" width="1" height="3" border="0" /></td>';
    strDiv = strDiv + '</tr></table>';
    //alert (strDiv);
    var myDiv = e("divFrom_10");
    myDiv.innerHTML = strDiv;
}

function addToBarItem(title, id) {
    var strDiv = '<table width="100%" border="0" cellpadding="0" cellspacing="0" id="tableline2">';
    strDiv = strDiv + '<tr><td width="30" height="3" colspan="3" background="images/table_line_bg.gif"><img src="images/spacer.gif" alt="" width="1" height="3" border="0" /></td>';
    strDiv = strDiv + '</tr><tr><td height="3" colspan="3" class="normalText"><img src="images/spacer.gif" alt="" width="1" height="3" border="0" /></td>';
    strDiv = strDiv + '</tr></table><table width="100%" border="0" cellpadding="0" cellspacing="0" id="roadname">';
    strDiv = strDiv + '<tr><td width="25" valign="top" class="normalText"><a href="#">' + (id + 1) + '.</a></td>';
    strDiv = strDiv + '<td width="5" class="normalText"><img src="images/spacer.gif" alt="" width="5" height="1" border="0" /></td>';
    strDiv = strDiv + '<td valign="top" class="normalText"><strong><a href="#" onclick="setStarMarker(' + gToLon[id] + ',' + gToLat[id] + ',&quot;' + gToName[id] + '&quot;)" >' + title + '</a></strong></td>';
    strDiv = strDiv + '<td width="23" valign="top" class="normalText"><div align="right">';
    strDiv = strDiv + '<table width="100%" border="0" cellspacing="0" cellpadding="0"><tr>';
    strDiv = strDiv + '<td><a href="#" onclick="setEndMarker(' + gToLon[id] + ',' + gToLat[id] + ',&quot;' + gToName[id] + '&quot;)"><img src="images/flag_b.gif" title="' + title_destination[langMod] + '" width="21" height="21" border="0" /></a></td>';
    strDiv = strDiv + '<td width="2"><img src="images/spacer.gif" alt="" width="5" height="1" border="0" /></td>';
    strDiv = strDiv + '</tr></table></div></td>';
    strDiv = strDiv + '</tr><tr><td height="3" colspan="3" class="normalText"><img src="images/spacer.gif" alt="" width="1" height="3" border="0" /></td>';
    strDiv = strDiv + '</tr></table>';
    
    var mDiv = "divTo_" + id;
    var myDiv = e(mDiv);
    myDiv.innerHTML = strDiv;
}

function addToBarFoot(title) {
    var strDiv = '<table width="100%" border="0" cellpadding="0" cellspacing="0" id="tableline2">';
    strDiv = strDiv + '<tr><td width="30" height="3" colspan="3" background="images/table_line_bg.gif"><img src="images/spacer.gif" alt="" width="1" height="3" border="0" /></td>';
    strDiv = strDiv + '</tr><tr><td height="3" colspan="3" class="normalText"><img src="images/spacer.gif" alt="" width="1" height="3" border="0" /></td>';
    strDiv = strDiv + '</tr></table><table width="100%" border="0" cellpadding="0" cellspacing="0" id="roadname">';
    strDiv = strDiv + '<tr><td width="25" valign="top" class="normalText"><a href="#"></a></td>';
    strDiv = strDiv + '<td width="5" class="normalText"><img src="images/spacer.gif" alt="" width="5" height="1" border="0" /></td>';
    strDiv = strDiv + '<td valign="top" align="right" class="normalText">' + title + '</td>';
    strDiv = strDiv + '</tr><tr><td height="3" colspan="3" class="normalText"><img src="images/spacer.gif" alt="" width="1" height="3" border="0" /></td>';
    strDiv = strDiv + '</tr></table>';
    
    var myDiv = e("divTo_10");
    myDiv.innerHTML = strDiv;
}

function addCategoryFoot(title) {
//  var strDiv = '<table width="100%" border="0" cellpadding="0" cellspacing="0" id="tableline2">';
//  strDiv = strDiv + '<tr><td width="30" height="3" colspan="3" background="images/table_line_bg.gif"><img src="images/spacer.gif" alt="" width="1" height="3" border="0" /></td>';
//  strDiv = strDiv + '</tr><tr><td height="3" colspan="3" class="normalText"><img src="images/spacer.gif" alt="" width="1" height="3" border="0" /></td>';
//  strDiv = strDiv + '</tr></table><table width="100%" border="0" cellpadding="0" cellspacing="0" id="roadname">';
    var strDiv = '<table width="100%" border="0" cellpadding="0" cellspacing="0" id="roadname">';
    strDiv = strDiv + '<tr><td width="25" valign="top" class="normalText"><a href="#"></a></td>';
    strDiv = strDiv + '<td width="5" class="normalText"><img src="images/spacer.gif" alt="" width="5" height="1" border="0" /></td>';
    strDiv = strDiv + '<td valign="top" align="right" class="normalText">' + title + '</td>';
    strDiv = strDiv + '</tr><tr><td height="3" colspan="3" class="normalText"><img src="images/spacer.gif" alt="" width="1" height="3" border="0" /></td>';
    strDiv = strDiv + '</tr></table>';
    
    var myDiv = e("divCate_10");
    myDiv.innerHTML = strDiv;
}

function addTourFoot(divName, title) {
    var strDiv = '<table width="100%" border="0" cellpadding="0" cellspacing="0" id="roadname">';
    strDiv = strDiv + '<tr><td width="25" valign="top" class="normalText"><a href="#"></a></td>';
    strDiv = strDiv + '<td width="5" class="normalText"><img src="images/spacer.gif" alt="" width="5" height="1" border="0" /></td>';
    strDiv = strDiv + '<td valign="top" align="right" class="normalText">' + title + '</td>';
    strDiv = strDiv + '</tr><tr><td height="3" colspan="3" class="normalText"><img src="images/spacer.gif" alt="" width="1" height="3" border="0" /></td>';
    strDiv = strDiv + '</tr></table>';
    
    var myDiv = e("div" + divName + "_10");
    myDiv.innerHTML = strDiv;
}

function addCategoryItem(title, id){
    var str='<table width="100%" border="0" cellpadding="0" cellspacing="0" id="hotelname"><tr>';
    str = str + '<td width="2" ><img src="images/spacer.gif" alt="" width="2" height="1" border="0" /></td>';
    str = str + '<td width="15" valign="top" class="normalText"><a href="#">' + (id+1) + '.</a></td>';
    str = str + '<td valign="top" class="normalText"><a href="#" onclick="setStarMarker(' + gCaLon[id] + ',' + gCaLat[id] + ',&quot;' + gCaName[id] + '&quot;)" >' + title + '</a></td>';
    str = str + '<td width="45" valign="top" class="normalText"><div align="right">';
    str = str + '<table width="100%" border="0" cellspacing="0" cellpadding="0"><tr>';
    str = str + '<td><a href="#" onclick="setStartMarker(' + gCaLon[id] + ',' + gCaLat[id] + ',&quot;' + gCaName[id] + '&quot;)"><img src="images/flag_a.gif" title="' + title_origin[langMod] + '" width="21" height="21" border="0" /></a></td>';
    str = str + '<td width="5"><img src="images/spacer.gif" alt="" width="5" height="1" border="0" /></td>';
    str = str + '<td><a href="#" onclick="setEndMarker(' + gCaLon[id] + ',' + gCaLat[id] + ',&quot;' + gCaName[id] + '&quot;)"><img src="images/flag_b.gif" title="' + title_destination[langMod] + '" width="21" height="21" border="0" /></a></td>';
    str = str + '</tr></table></div></td></tr></table>';
    str = str + '<table width="100%" border="0" cellpadding="0" cellspacing="0" id="tableblankline"><tr>';
    str = str + '<td height="3" colspan="5" ><img src="images/spacer.gif" alt="" width="1" height="3" border="0" /></td>';
    str = str + '</tr></table>';
    str = str + '<table width="100%" border="0" cellpadding="0" cellspacing="0" id="tableline"><tr>';
    str = str + '<td width="30" height="3" colspan="3" background="images/table_line_bg.gif"><img src="images/spacer.gif" alt="" width="1" height="3" border="0" /></td></tr><tr>';
    str = str + '<td height="3" colspan="3" ><img src="images/spacer.gif" alt="" width="1" height="3" border="0" /></td>';
    str = str + '</tr></table>';
   
  var mDiv = "divCate_" + id;
    var myDiv = e(mDiv);
    myDiv.innerHTML = str;
    
}

function addCategoryItem_NULL(title, id){
    var str='<table width="100%" border="0" cellpadding="0" cellspacing="0" id="hotelname"><tr>';
    str = str + '<td width="2" ><img src="images/spacer.gif" alt="" width="2" height="1" border="0" /></td>';
    str = str + '<td valign="top" class="normalText">' + dispNoRecordFound[langMod] + '</td>';
    str = str + '<td width="45" valign="top" class="normalText"><div align="right">';
    str = str + '<table width="100%" border="0" cellspacing="0" cellpadding="0"><tr>';
    str = str + '<td></td>';
    str = str + '<td width="5"><img src="images/spacer.gif" alt="" width="5" height="1" border="0" /></td>';
    str = str + '<td></td>';
    str = str + '</tr></table></div></td></tr></table>';
    str = str + '<table width="100%" border="0" cellpadding="0" cellspacing="0" id="tableblankline"><tr>';
    str = str + '<td height="3" colspan="5" ><img src="images/spacer.gif" alt="" width="1" height="3" border="0" /></td>';
    str = str + '</tr></table>';
    str = str + '<table width="100%" border="0" cellpadding="0" cellspacing="0" id="tableline"><tr>';
    str = str + '<td width="30" height="3" colspan="3" background="images/table_line_bg.gif"><img src="images/spacer.gif" alt="" width="1" height="3" border="0" /></td></tr><tr>';
    str = str + '<td height="3" colspan="3" ><img src="images/spacer.gif" alt="" width="1" height="3" border="0" /></td>';
    str = str + '</tr></table>';
   
  var mDiv = "divCate_0";
    var myDiv = e(mDiv);
    myDiv.innerHTML = str;
    
}

function addTourItem(divName,id, title, myID){
    var str='<table width="100%" border="0" cellpadding="0" cellspacing="0" id="hotelname"><tr>';
    str = str + '<td width="2" ><img src="images/spacer.gif" alt="" width="2" height="1" border="0" /></td>';
    str = str + '<td width="15" valign="top" class="normalText"><a href="#">' + (id+1) + '.</a></td>';
    str = str + '<td valign="top" class="normalText"><a href="#" onclick="setStarMarker(' + gTaLon[myID] + ',' + gTaLat[myID] + ',&quot;' + gTaName[myID] + '&quot;)" >' + title + '</a></td>';
    str = str + '<td width="45" valign="top" class="normalText"><div align="right">';
    str = str + '<table width="100%" border="0" cellspacing="0" cellpadding="0"><tr>';
    str = str + '<td><a href="#" onclick="setStartMarker(' + gTaLon[myID] + ',' + gTaLat[myID] + ',&quot;' + gTaName[myID] + '&quot;)" ><img src="images/flag_a.gif" title="' + title_origin[langMod] + '" width="21" height="21" border="0" /></a></td>';
    str = str + '<td width="5"><img src="images/spacer.gif" alt="" width="5" height="1" border="0" /></td>';
    str = str + '<td><a href="#" onclick="setEndMarker(' + gTaLon[myID] + ',' + gTaLat[myID] + ',&quot;' + gTaName[myID] + '&quot;)" ><img src="images/flag_b.gif" title="' + title_destination[langMod] + '" width="21" height="21" border="0" /></a></td>';
    str = str + '</tr></table></div></td></tr></table>';
    str = str + '<table width="100%" border="0" cellpadding="0" cellspacing="0" id="tableblankline"><tr>';
    str = str + '<td height="3" colspan="5" ><img src="images/spacer.gif" alt="" width="1" height="3" border="0" /></td>';
    str = str + '</tr></table>';
    str = str + '<table width="100%" border="0" cellpadding="0" cellspacing="0" id="tableline"><tr>';
    str = str + '<td width="30" height="3" colspan="3" background="images/table_line_bg.gif"><img src="images/spacer.gif" alt="" width="1" height="3" border="0" /></td></tr><tr>';
    str = str + '<td height="3" colspan="3" ><img src="images/spacer.gif" alt="" width="1" height="3" border="0" /></td>';
    str = str + '</tr></table>';
   
    var myDiv = e(divName);
    myDiv.innerHTML = str;
    
}

function changeHarbourItem(nodeID, myPermit){
    
        //***************090520*********************************
        //CROSS HARBOUR TUNNEL /  WESTERN HARBOUR CROSSING /  EASTERN HARBOUR CROSSING
        //left: 16798 / 15203  / 16007
        //right: 16800  / 15202 / 16009
        //node
        //left:  16798 /  15203  / 16007 
        //right:  16800  / 15202  / 16009 
    
    var divPathResult = document.getElementById('pathResult');
    if (nodeID!=0 && myPermit!=0){
        divPathResult.style.height = (w_height - 410) + 'px';
    }else if(nodeID!=0){
        divPathResult.style.height = (w_height - 390) + 'px';
    }else if(myPermit!=0){
        divPathResult.style.height = (w_height - 360) + 'px';
    }else{
        return; 
    }
    
    var harbID1, harbID2, img1, img2;
    if (nodeID == crossingList[0][0]){
            harbID1=crossingList[1][0];
            harbID2=crossingList[2][0];
        if (lang=='E')
        {
            img1="WHC.jpg";
            img2="EHC.jpg";
        }else{
            img1="WHC_C.jpg";
            img2="EHC_C.jpg";
        }

    }
    if (nodeID == crossingList[1][0]){
        harbID1=crossingList[0][0];
        harbID2=crossingList[2][0];
        if (lang=='E')
        {
            img1="CHT.jpg";
            img2="EHC.jpg";
        }else{
            img1="CHT_C.jpg";
            img2="EHC_C.jpg";
        }
    }
    if (nodeID == crossingList[2][0]){
        harbID1=crossingList[0][0];
        harbID2=crossingList[1][0];
        if (lang=='E')
        {
            img1="CHT.jpg";
            img2="WHC.jpg";
        }else{
            img1="CHT_C.jpg";
            img2="WHC_C.jpg";
        }

    }

    if (nodeID == crossingList[3][0]){
        harbID1=crossingList[4][0];
        harbID2=crossingList[5][0];
        if (lang=='E')
        {
            img1="WHC.jpg";
            img2="EHC.jpg";
        }else{
            img1="WHC_C.jpg";
            img2="EHC_C.jpg";
        }
    }
    if (nodeID == crossingList[4][0]){
        harbID1=crossingList[3][0];
        harbID2=crossingList[5][0];
        if (lang=='E')
        {
            img1="CHT.jpg";
            img2="EHC.jpg";
        }else{      
            img1="CHT_C.jpg";
            img2="EHC_C.jpg";
        }
    }
    if (nodeID == crossingList[5][0]){
        harbID1=crossingList[3][0];
        harbID2=crossingList[4][0];
        if (lang=='E')
        {
            img1="CHT.jpg";
            img2="WHC.jpg";
        }else{
            img1="CHT_C.jpg";
            img2="WHC_C.jpg";
        }
    }
    
    var str='';
    if (myPermit!=0){
        //fjdlkafjdlsajfl
        str = '<table width="100%" border="0" cellspacing="0" cellpadding="0"><tr><td>'
            + '<div><strong class="normalPointText"><font color=red>' + dispDesc3[langMod] + '</font></strong></div>'
            + '</td></tr><tr><td height="3" colspan="6" background="images/table_line_bg.gif"><img src="images/spacer.gif" alt="" width="1" height="3" border="0" /></td>'
            + '</tr></table>';  
            

    }
    if (nodeID!=0){
        str=str + '<table width="100%" border="0" cellspacing="0" cellpadding="0"><tr>'
        + '<td><table width="100%" border="0" cellspacing="0" cellpadding="0">'
        + '<tr><td nowrap="nowrap"><strong class="normalPointText">' + dispResult[langMod] + ':</strong></td></tr>'
        + '<tr><td><table width="100%" border="0" cellspacing="0" cellpadding="0"><tr>'
        + '<td nowrap="nowrap" class="normalText"><div id="pathIMG"></div></td>'
        + '<td><table width="100%" border="0" cellspacing="0" cellpadding="0">'
        + '<tr><td nowrap="nowrap" class="normalText">' + dispDistance[langMod] + ':</td>'
        + '<td nowrap="nowrap" class="normalText"><div id="pathDistance"></div></td></tr>'
        + '<tr><td nowrap="nowrap" class="normalTexttime">' + dispTime[langMod] + ':</td>'
        + '<td nowrap="nowrap"><span class="normalTexttime"><div id="pathTime"></div></span></td>'
        + '<tr><td nowrap="nowrap" class="normalText">' + dispToll[langMod] + ':</td>'
        + '<td nowrap="nowrap"><span class="normalText"><div id="pathToll"></div></span></td>'
        + '</tr></table></td></tr></table></td></tr></table></td>'
        
        + '<td width="10px" background="images/table_side_bg.gif"></td>'
        
        + '<td><table width="100%" border="0" cellspacing="0" cellpadding="0"><tr>'
        + '<td nowrap="nowrap"><strong class="normalPointText">' + dispOtherOption[langMod] + ':</strong></td></tr>'
        + '<tr><td><table width="100%" border="0" cellspacing="0" cellpadding="0"><tr>'
        + '<td><a href="#" onclick="getSP(' + harbID1 + ')"><img src="images/' + img1 + '" alt="" width="44" height="40" border="0" /></a></td>'
        + '<td><table width="100%" border="0" cellspacing="0" cellpadding="0">'
        + '<tr><td nowrap="nowrap" class="normalText"><div id="harbLen1"></div></td></tr>'
        + '<tr><td nowrap="nowrap"><span class="normalTexttime"><div id="harbTime1"></div></span></td></tr>'
        + '<tr><td nowrap="nowrap"><span class="normalText"><div id="harbToll1"></div></span></td></tr></table></td>'
        + '<td><a href="#" onclick="getSP(' + harbID2 + ')"><img src="images/' + img2 + '" alt="" width="44" height="40" border="0" /></a></td>'
        + '<td><table width="100%" border="0" cellspacing="0" cellpadding="0">'
        + '<tr><td nowrap="nowrap" class="normalText"><div id="harbLen2"></div></td></tr>'
        + '<tr><td nowrap="nowrap"><span class="normalTexttime"><div id="harbTime2"></div></span></td></tr>'
        + '<tr><td nowrap="nowrap"><span class="normalText"><div id="harbToll2"></div></span></td></tr>'
        + '</table></td></tr></table>';
    //  + '<td width="500" height="10" background="images/table_top_bg.gif"><img src="images/spacer.gif" alt="" width="8" height="10" border="0" /></td>';  
        + '</td></tr></table></td></tr></table>';
    }else{
        //result
            
        str = str   + '<table width="100%" border="0" cellspacing="0" cellpadding="0">'
        + '<tr>'
            + '<td nowrap="nowrap"><strong class="normalPointText">' + dispResult[langMod] + ':</strong></td>'
            + '<td nowrap="nowrap" class="normalText"></td>'
              + '<td align="right" nowrap="nowrap" class="normalText">' + dispDistance[langMod] + ':</td>'
              + '<td nowrap="nowrap" class="normalText"><div id="pathDistance"></div></td>'
                + '<td align="right" nowrap="nowrap" class="normalText">' + dispTime[langMod] + ':</td>'
                + '<td nowrap="nowrap"><span class="normalText"><div id="pathTime"></div></span></td>'
                + '<td align="right" nowrap="nowrap" class="normalText">' + dispToll[langMod] + ':</td>'
                + '<td nowrap="nowrap"><span class="normalText"><div id="pathToll"></div></span></td>'
            + '</tr>'
            + '</table>';   
    }
    var divPRI = document.getElementById('pathResultInfo');
    divPRI.innerHTML = str;
}

function clearBar(){
    var w_height_FT=(w_height - 333)/2;
    var ul=document.getElementById('s3_content');
    var strIn = '<div id="roadSearchMainDiv">';
    strIn = strIn + '<table width="100%" border="0" cellspacing="0" cellpadding="0"><tr>';
    strIn = strIn + '<td width="8" height="10"><img src="images/spacer.gif" alt="" width="8" height="10" border="0" /></td>';
    strIn = strIn + '<td width="1173" height="10" background="images/table_top_bg.gif"><img src="images/spacer.gif" alt="" width="8" height="10" border="0" /></td>';
    strIn = strIn + '<td width="5" height="10" bgcolor="#FFFFFF"><img src="images/spacer.gif" alt="" width="5" height="10" border="0" /></td>';
    
    strIn = strIn + '</tr></table><table width="100%" border="0" cellpadding="0" cellspacing="0" id="from">';
    strIn = strIn + '<tr><td width="13" valign="top"><img src="images/spacer.gif" alt="" width="13" height="13" border="0" /></td>';
    strIn = strIn + '<td><span class="normalText"><strong class="normalPointText">' + dispFrom[langMod] + '</strong><br /></span> ';
    strIn = strIn + '<div id="s3_content_from" style="height: ' + w_height_FT + 'px; width: 100%; overflow-x: hidden; overflow-y: auto;">';
    strIn = strIn + '<div id="divFrom_0" style=" margin-right: 1px; display:inline;"></div><div id="divFrom_1" style=" margin-right: 1px; display:inline;"></div><div id="divFrom_2" style=" margin-right: 1px; display:inline;"></div><div id="divFrom_3" style=" margin-right: 1px; display:inline;"></div><div id="divFrom_4" style=" margin-right: 1px; display:inline;"></div><div id="divFrom_5" style=" margin-right: 1px; display:inline;"></div>';
    strIn = strIn + '<div id="divFrom_6" style=" margin-right: 1px; display:inline;"></div><div id="divFrom_7" style=" margin-right: 1px; display:inline;"></div><div id="divFrom_8" style=" margin-right: 1px; display:inline;"></div><div id="divFrom_9" style=" margin-right: 1px; display:inline;"></div><div id="divFrom_10" style=" margin-right: 1px; display:inline;"></div></div>';
    strIn = strIn + '</td><td width="5"><img src="images/spacer.gif" alt="" width="5" height="10" border="0" /></td>';
    strIn = strIn + '</tr></table><table width="100%" border="0" cellpadding="0" cellspacing="0" id="tableclose">';
    strIn = strIn + '<tr><td height="4" colspan="3"><img src="images/spacer.gif" alt="" width="8" height="4" border="0" /></td>';
    strIn = strIn + '</tr><tr><td width="8" height="10"><img src="images/spacer.gif" alt="" width="8" height="10" border="0" /></td>';
    strIn = strIn + '<td height="10" background="images/table_top_bg.gif"><img src="images/spacer.gif" alt="" width="8" height="10" border="0" /></td>';
    strIn = strIn + '<td width="5" height="10"><img src="images/spacer.gif" alt="" width="5" height="10" border="0" /></td>';
    
    strIn = strIn + '</tr></table><table width="100%" border="0" cellpadding="0" cellspacing="0" id="to">';
    strIn = strIn + '<tr><td width="13" valign="top"><img src="images/spacer.gif" alt="" width="13" height="13" border="0" /></td>';
    strIn = strIn + '<td><span class="normalText"><strong class="normalPointText">' + dispTo[langMod] + '</strong><br /></span>';
    strIn = strIn + '<div id="s3_content_to" style="height: ' + w_height_FT + 'px; width: 100%; overflow-x: hidden; overflow-y: auto;">';
    strIn = strIn + '<div id="divTo_0" style=" margin-right: 1px; display:inline;"></div><div id="divTo_1" style=" margin-right: 1px; display:inline;"></div><div id="divTo_2" style=" margin-right: 1px; display:inline;"></div><div id="divTo_3" style=" margin-right: 1px; display:inline;"></div><div id="divTo_4" style=" margin-right: 1px; display:inline;"></div><div id="divTo_5" style=" margin-right: 1px; display:inline;"></div>';
    strIn = strIn + '<div id="divTo_6" style=" margin-right: 1px; display:inline;"></div><div id="divTo_7" style=" margin-right: 1px; display:inline;"></div><div id="divTo_8" style=" margin-right: 1px; display:inline;"></div><div id="divTo_9" style=" margin-right: 1px; display:inline;"></div><div id="divTo_10" style=" margin-right: 1px; display:inline;"></div></div>';
    strIn = strIn + '</td><td width="5"><img src="images/spacer.gif" alt="" width="5" height="10" border="0" /></td>';
    strIn = strIn + '</tr></table><table width="100%" border="0" cellpadding="0" cellspacing="0" id="tableclose2">';
    strIn = strIn + '<tr><td height="4" colspan="3"><img src="images/spacer.gif" alt="" width="8" height="4" border="0" /></td>';
    strIn = strIn + '</tr><tr><td width="8" height="10"><img src="images/spacer.gif" alt="" width="8" height="10" border="0" /></td>';
    strIn = strIn + '<td height="10" background="images/table_top_bg.gif"><img src="images/spacer.gif" alt="" width="8" height="10" border="0" /></td>';
    strIn = strIn + '<td width="5" height="10"><img src="images/spacer.gif" alt="" width="5" height="10" border="0" /></td>';
    
    strIn = strIn + '</tr></table></div>';
    ul.innerHTML = strIn;

}

function init_pathResult(){

    clearTimeVariable();
    
    time2 = getTimeNow();
    //var w_height_R= w_height - 440;
    var w_height_R= w_height - 340;
    var ul=document.getElementById('s3_content');
    
    var strIn = '<div id="roadSearchMainDiv">';
    strIn = strIn + '<table width="100%" border="0" cellspacing="0" cellpadding="0"><tr>';
    strIn = strIn + '<td width="8" height="10"><img src="images/spacer.gif" alt="" width="8" height="10" border="0" /></td>';
    strIn = strIn + '<td width="1173" height="10" background="images/table_top_bg.gif"><img src="images/spacer.gif" alt="" width="8" height="10" border="0" /></td>';
    strIn = strIn + '<td width="5" height="10" bgcolor="#FFFFFF"><img src="images/spacer.gif" alt="" width="5" height="10" border="0" /></td></tr></table>';
    
    
    strIn = strIn + '<table width="100%" border="0" cellpadding="0" cellspacing="0" id="from">'
    + '<tr>'
    + '<td width="13" valign="top"><img src="images/spacer.gif" alt="" width="13" height="13" border="0" /></td>'
  + '<td>';
/*
    //Avoid a road      Include a road   
    strIn = strIn + '<table width="100%" border="0" cellspacing="0" cellpadding="0">'
        + '<tr>'
            + '<td width="25"><input name="aiOption" type="radio" id="avoidroad" value="avoidroad" checked onClick="setAvoidroad()"/></td>'
            + '<td width="115" nowrap="nowrap"><strong class="normalPointText">' + dispAvoid[langMod] + '</strong></td>'
            + '<td width="25" class="normalText"><input name="aiOption" type="radio" id="includeroad" value="includeroad" onClick="setIncluderoad()"/></td>'
            + '<td width="115" nowrap="nowrap" ><strong class="normalPointText">' + dispInclude[langMod] + '<trong></td><td class="normalText">&nbsp;</td>'
            + '<td width="5" class="normalText"><img src="images/spacer.gif" alt="" width="5" height="5" border="0" /></td>'
        + '</tr>'
        + '<tr>'
            + '<td colspan="5" class="normalText"><select name="roadList" class="form-fields-small" id="roadList" onchange="changeAI(this.options[this.options.selectedIndex].value)">';
            for (var i=0; i < avoidArr.length; i++){
                strIn = strIn + '<option value="' + avoidArr[i][3] + '">' + avoidArr[i][langMod] + '</option>';
            }
            strIn = strIn + '</select></td>'
            + '<td width="5" class="normalText"><img src="images/spacer.gif" alt="" width="5" height="5" border="0" /></td>'
        + '</tr>'
        + '<tr>'
            + '<td height="3" colspan="6"><span class="normalText"><img src="images/spacer.gif" alt="" width="5" height="3" border="0" /></span></td>'
        + '</tr>'
        
        + '<tr>'
            + '<td height="3" colspan="6" background="images/table_line_bg.gif"><img src="images/spacer.gif" alt="" width="1" height="3" border="0" /></td>'
        + '</tr>'
        
    + '</table>';
*/
    //Total Distance:   Travel Time: 
  strIn = strIn + '<div id="pathResultInfo">'
        + '<table width="100%" border="0" cellspacing="0" cellpadding="0">'
        + '<tr>'
            + '<td nowrap="nowrap"><strong class="normalPointText">' + dispResult[langMod] + ':</strong></td>'
            + '<td nowrap="nowrap" class="normalText"></td>'
              + '<td align="right" nowrap="nowrap" class="normalText">' + dispDistance[langMod] + ':</td>'
              + '<td nowrap="nowrap" class="normalText"><div id="pathDistance"></div></td>'
                + '<td align="right" nowrap="nowrap" class="normalText">' + dispTime[langMod] + ':</td>'
                + '<td nowrap="nowrap"><span class="normalText"><div id="pathTime"></div></span></td>'
                + '<td align="right" nowrap="nowrap" class="normalText">' + dispToll[langMod] + ':</td>'
                + '<td nowrap="nowrap"><span class="normalText"><div id="pathToll"></div></span></td>'
            + '</tr>'
            + '</table>'
            + '</div>'
            + '<table width="100%" border="0" cellspacing="0" cellpadding="0"><tr>'
                + '<td height="3" colspan="2"><img src="images/spacer.gif" alt="" width="3" height="3" border="0" /></td>'
            + '</tr></table>';
    
    strIn = strIn + '</td>'
    + '<td width="5"><img src="images/spacer.gif" alt="" width="5" height="10" border="0" /></td>'
    + '</tr>'
    + '</table>';
    
    //bold line
    strIn = strIn + '<table width="100%" border="0" cellpadding="0" cellspacing="0" id="tableclose">';
    strIn = strIn + '<tr><td height="4" colspan="3"><img src="images/spacer.gif" alt="" width="8" height="4" border="0" /></td></tr>';
    strIn = strIn + '<tr><td width="9" height="10"><img src="images/spacer.gif" alt="" width="8" height="10" border="0" /></td>';
    strIn = strIn + '<td width="1174" height="10" background="images/table_top_bg.gif"><img src="images/spacer.gif" alt="" width="8" height="10" border="0" /></td>';
    strIn = strIn + '<td width="5" height="10"><img src="images/spacer.gif" alt="" width="5" height="10" border="0" /></td></tr></table>';
//result  list
    strIn = strIn + '<table width="100%" border="0" cellpadding="0" cellspacing="0" id="result"><tr>';
    strIn = strIn + '<td width="13" valign="top"><img src="images/spacer.gif" alt="" width="13" height="13" border="0" /></td>';
    strIn = strIn + '<td><div id="pathResult" style="height: ' + w_height_R + 'px; width: 100%; overflow-x: hidden; overflow-y: auto;"></div></td>';
    strIn = strIn + '<td width="5"><img src="images/spacer.gif" alt="" width="5" height="10" border="0" /></td></tr></table>';

    strIn = strIn + '<table width="100%" border="0" cellpadding="0" cellspacing="0" id="tableclose2">';
    strIn = strIn + '<tr> <td height="4" colspan="3"><img src="images/spacer.gif" alt="" width="8" height="4" border="0" /></td></tr>';
    strIn = strIn + '<tr><td width="9" height="10"><img src="images/spacer.gif" alt="" width="8" height="10" border="0" /></td>';
    strIn = strIn + '<td width="1174" height="10" background="images/table_top_bg.gif"><img src="images/spacer.gif" alt="" width="8" height="10" border="0" /></td>';
    strIn = strIn + '<td width="5" height="10"><img src="images/spacer.gif" alt="" width="5" height="10" border="0" /></td></tr></table>';
    
    strIn = strIn + '<table width="100%" border="0" cellpadding="0" cellspacing="0" id="rbuttons">';
    strIn = strIn + '<tr><td width="13" height="27" valign="top" ><img src="images/spacer.gif" alt="" width="13" height="13" border="0" /></td>';
    strIn = strIn + '<td width="55" height="27" valign="top" ><a href="#" onclick="goBack()">';
    if (lang=='E'){
        strIn = strIn + '<img src="images/back.gif" alt="" width="55" height="27" border="0" /></a></td>';
        strIn = strIn + '<td class="normalText">&nbsp;</td>';
        strIn = strIn + '<td width="97" height="27" valign="top" ><a href="#" onclick="showRoutes()">';
        strIn = strIn + '<img src="images/print_routes.gif" alt="" width="97" height="27" border="0" /></a></td>';
    }else if (lang=='TC'){
        strIn = strIn + '<img src="big5/images/back.gif" alt="" width="55" height="27" border="0" /></a></td>';
        strIn = strIn + '<td class="normalText">&nbsp;</td>';
        strIn = strIn + '<td width="97" height="27" valign="top" ><a href="#" onclick="showRoutes()">';
        strIn = strIn + '<img src="big5/images/print_routes.gif" alt="" width="97" height="27" border="0" /></a></td>';
    }else if (lang=='SC'){
        strIn = strIn + '<img src="gb/images/back.gif" alt="" width="55" height="27" border="0" /></a></td>';
        strIn = strIn + '<td class="normalText">&nbsp;</td>';
        strIn = strIn + '<td width="97" height="27" valign="top" ><a href="#" onclick="showRoutes()">';
        strIn = strIn + '<img src="gb/images/print_routes.gif" alt="" width="97" height="27" border="0" /></a></td>';
    }else{
        strIn = strIn + '<img src="images/back.gif" alt="" width="55" height="27" border="0" /></a></td>';
        strIn = strIn + '<td class="normalText">&nbsp;</td>';
        strIn = strIn + '<td width="97" height="27" valign="top" ><a href="#" onclick="showRoutes()">';
        strIn = strIn + '<img src="images/print_routes.gif" alt="" width="97" height="27" border="0" /></a></td>';
    }
    strIn = strIn + '<td width="5" valign="top" ><img src="images/spacer.gif" alt="" width="5" height="13" border="0" /></td></tr></table></div>';
    ul.innerHTML = strIn;

    time3 = getTimeNow();

}

function setAvoidroad(){
    var roadList = e('roadList');
    roadList.options.length = 0;
    for (var i=0; i < avoidArr.length; i++){
        var newItem = new Option(avoidArr[i][langMod],avoidArr[i][3]); 
        roadList.options.add(newItem);
    }
}

function setIncluderoad(){
    var roadList = e('roadList');
    roadList.options.length = 0;
    for (var i=0; i < includeArr.length; i++){
        var newItem = new Option(includeArr[i][langMod],includeArr[i][3]); 
        roadList.options.add(newItem);
    }
}

function changeAI(roadList){
    if (e("avoidroad").checked){
        if (roadList!="skip"){
            getSP(roadList);
        }
    }else{
        if (roadList!="skip"){
            //Here is coord, not road list
            var arrTemp = roadList.split(",");
            var xMid=arrTemp[0];
            var yMid=arrTemp[1];
            getSPM(xMid,yMid);
        }
    }
}

function clearInputFrom(){
    fromLon = '';
    fromLat = '';
    fromLon_ = '';
    fromLat_ = '';
    fromName = '';
    if (markerStart){
        layerMarkers.removeFeatures(markerStart);
    }
    clearLine();
    clearSkipInclude();
    // Henry
    hideAvoidToolbar();
}

function clearInputTo(){
    toLon = '';
    toLat = '';
    toLon_ = '';
    toLat_ = '';
    toName = '';
    if (markerEnd){
        layerMarkers.removeFeatures(markerEnd);
    }
    clearLine();
    clearSkipInclude();
    // Henry
    hideAvoidToolbar();
}

function clearSkipInclude(){
    for (var i=0; i<gSkipInt; i++){
        layerMarkers.removeFeatures(gSkipMarker[i]);    
    }
    gSkipInt = 0;
    gSkipLon = [];
    gSkipLat = [];
    gSkipMarker = [];
    gSkipNode = [];
    
    for (var i=0; i<gIncludeInt; i++){
        layerMarkers.removeFeatures(gIncludeMarker[i]); 
    }
    gIncludeInt = 0;
    gIncludeLon = [];
    gIncludeLat = [];
    gIncludeMarker = [];
}

function clearFromBar(){
    e('divFrom_0').innerHTML="";
    e('divFrom_1').innerHTML="";
    e('divFrom_2').innerHTML="";
    e('divFrom_3').innerHTML="";
    e('divFrom_4').innerHTML="";
    e('divFrom_5').innerHTML="";
    e('divFrom_6').innerHTML="";
    e('divFrom_7').innerHTML="";
    e('divFrom_8').innerHTML="";
    e('divFrom_9').innerHTML="";
    e('divFrom_10').innerHTML="";
}

function clearToBar(){
    e('divTo_0').innerHTML="";
    e('divTo_1').innerHTML="";
    e('divTo_2').innerHTML="";
    e('divTo_3').innerHTML="";
    e('divTo_4').innerHTML="";
    e('divTo_5').innerHTML="";
    e('divTo_6').innerHTML="";
    e('divTo_7').innerHTML="";
    e('divTo_8').innerHTML="";
    e('divTo_9').innerHTML="";
    e('divTo_10').innerHTML="";
}

function clearCateBar(){
    e('divCate_0').innerHTML="";
    e('divCate_1').innerHTML="";
    e('divCate_2').innerHTML="";
    e('divCate_3').innerHTML="";
    e('divCate_4').innerHTML="";
    e('divCate_5').innerHTML="";
    e('divCate_6').innerHTML="";
    e('divCate_7').innerHTML="";
    e('divCate_8').innerHTML="";
    e('divCate_9').innerHTML="";
    e('divCate_10').innerHTML="";
}

function clearTourBar(myDist){
    var divName = 'div' + myDist + '_0';
    e(divName).innerHTML="";
    divName = 'div' + myDist + '_1';
    e(divName).innerHTML="";
    divName = 'div' + myDist + '_2';
    e(divName).innerHTML="";
    divName = 'div' + myDist + '_3';
    e(divName).innerHTML="";
    divName = 'div' + myDist + '_4';
    e(divName).innerHTML="";
    divName = 'div' + myDist + '_5';
    e(divName).innerHTML="";
    divName = 'div' + myDist + '_6';
    e(divName).innerHTML="";
    divName = 'div' + myDist + '_7';
    e(divName).innerHTML="";
    divName = 'div' + myDist + '_8';
    e(divName).innerHTML="";
    divName = 'div' + myDist + '_9';
    e(divName).innerHTML="";
    divName = 'div' + myDist + '_10';
    e(divName).innerHTML="";
}

function changeBodyClass(from, to) {
     document.body.className = document.body.className.replace(from, to);
     return false;
}   
    
function windowHeight() {
    // Standard browsers (Mozilla, Safari, etc.)
    if (self.innerHeight)
        return self.innerHeight;
    // IE 6
    if (document.documentElement && document.documentElement.clientHeight)
        return document.documentElement.clientHeight;
    // IE 5
    if (document.body)
        return document.body.clientHeight;
    // Just in case. 
    return 0;
}

function windowWidth() {
    // Standard browsers (Mozilla, Safari, etc.)
    if (self.innerWidth)
        return self.innerWidth;
    // IE 6
    if (document.documentElement && document.documentElement.clientWidth)
        return document.documentElement.clientWidth;
    // IE 5
    if (document.body)
        return document.body.clientWidth;
    // Just in case. 
    return 0;
}

function handleResize() {
    var main_table = e("main_table");
    //roadSearchMainDiv
    var s3_div = e("s3_content");
    var s2_div = e("s2_div");
    
    var map_div = document.getElementById("map_div");
    var toggle_div = document.getElementById("toggle_div");
    var list_div = document.getElementById("list_div");
    
    if (w_width>360){
        if (lang=="E"){
            e("from").style.width = parseInt(w_width * 0.36 - 217) + 'px';
            e("to").style.width = parseInt(w_width * 0.36 - 217) + 'px';
        }else{
            e("from").style.width = parseInt(w_width * 0.36 - 180) + 'px';
            e("to").style.width = parseInt(w_width * 0.36 - 180) + 'px';
        }
        list_div.style.width = parseInt(w_width * 0.36) + 'px';
        
        
    }
    if (w_height>64){
        main_table.style.height = (w_height - 64) + 'px';
        if (w_height>164){
            map_div.style.height = (w_height - 164) + 'px';
        }
    }
    
    if (w_height - 260 < 0){        
        s3_div.style.height = '0px';
    }else {
        try{
            s3_div.style.height = (w_height - 260) + 'px';
        }
        catch(err){
            //alert(err);
        }
    }
    
    if (e("s3_content_from")){
        if (w_height - 333 < 0){
            e("s3_content_from").style.display = 'none';
        } else {
            e("s3_content_from").style.display = 'block';
            e("s3_content_from").style.height = (w_height - 333)/2 + 'px';
        }
    }
    if (e("s3_content_to")){
        if (w_height - 333 < 0){
            e("s3_content_to").style.display = 'none';
        } else {
            e("s3_content_to").style.display = 'block';
            e("s3_content_to").style.height = (w_height - 333)/2 + 'px';
        }
    }
    if (e("categoryResultDiv")){
        if (w_height - 380 < 0){
            e("categoryResultDiv").style.display = 'none';
        } else {
            e("categoryResultDiv").style.display = 'block';
            e("categoryResultDiv").style.height = (w_height - 380) + 'px';
        }
    }
    
    if (e("tourismMainDiv")){
        if (w_height - 270 < 0){
            e("tourismMainDiv").style.display = 'none';
        } else {
            e("tourismMainDiv").style.display = 'block';
            e("tourismMainDiv").style.height = (w_height - 270) + 'px';
        }
    }
    //s2_div.style.display = 'none';
}

function swithTab(id){
    var s2_div=document.getElementById('s2_div');
    var s2_content=document.getElementById('s2_content');
    var s3_content=document.getElementById('s3_content');
    var s4_content=document.getElementById('s4_content');
    
    if (currentTabID == id){
        return; 
    }else{
        currentTabID = id;
        if (id==1){
            //will do something to keep the result
            s2_div.style.display = "none";
            s2_content.innerHTML = "";
            
            s3_content.innerHTML = TabHtml_1;
            
            var strS4= '<table width="100%" border="0" cellspacing="0" cellpadding="0">';
            strS4 = strS4 + '<tr><td height="5" width="320"><img src="images/spacer.gif" alt="" width="5" height="5" border="0"></td></tr>';
            strS4 = strS4 + genTabTitle(2, "cat_search.gif");
            strS4 = strS4 + '<tr><td height="5" width="320"><img src="images/spacer.gif" alt="" width="5" height="5" border="0"></td></tr>';
            strS4 = strS4 + genTabTitle(3, "tourism_board.gif");
            strS4 = strS4 + '<tr><td height="5" width="320"><img src="images/spacer.gif" alt="" width="5" height="5" border="0"></td></tr></table>';
            s4_content.innerHTML = strS4;
            
        }else if (id==2){
            s2_div.style.display = '';
            s2_div.style.height = '19px';
            var strS2= '<table width="100%" border="0" cellspacing="0" cellpadding="0">';
            strS2 = strS2 + genTabTitle(2, "cat_search.gif");
            strS2 = strS2 + '<tr><td height="5" width="320"><img src="images/spacer.gif" alt="" width="5" height="5" border="0"></td></tr></table>';
            s2_content.innerHTML = strS2;
            
            s3_content.innerHTML = TabHtml_2;
            
            var strS4= '<table width="100%" border="0" cellspacing="0" cellpadding="0">';
            strS4 = strS4 + '<tr><td height="5" width="320"><img src="images/spacer.gif" alt="" width="5" height="5" border="0"></td></tr>';
            strS4 = strS4 + genTabTitle(3, "tourism_board.gif");
            strS4 = strS4 + '<tr><td height="5" width="320"><img src="images/spacer.gif" alt="" width="5" height="5" border="0"></td></tr></table>';
            s4_content.innerHTML = strS4;

            
        }else if (id==3){
            s2_div.style.display = '';
            s2_div.style.height = '38px';
            var strS2= '<table width="100%" border="0" cellspacing="0" cellpadding="0">';
            strS2 = strS2 + genTabTitle(2, "cat_search.gif");
            strS2 = strS2 + '<tr><td height="5" width="320"><img src="images/spacer.gif" alt="" width="5" height="5" border="0"></td></tr>';
            strS2 = strS2 + genTabTitle(3, "tourism_board.gif");
            strS2 = strS2 + '<tr><td height="5" width="320"><img src="images/spacer.gif" alt="" width="5" height="5" border="0"></td></tr></table>';
            s2_content.innerHTML = strS2;
            
            s3_content.innerHTML = TabHtml_3;
            
            var strS4= '';
            s4_content.innerHTML = strS4;   
            s4_content.display="none";
            
            for(var i=0; i < arrTourism.length; i++){
                getTourism(true,arrTourism[i], i)
            }
        }
        handleResize();
    }
    
}

function swithCategory(id){
//  var w_height = windowHeight();
    var w_height_FT=(w_height - 380);
    var ul=document.getElementById('s3_content');
    var strIn = '<div id="categoryMainDiv">';
    strIn = strIn + '<table width="100%" border="0" cellpadding="0" cellspacing="0" id="from">';
    strIn = strIn + '<tr><td> ';
    strIn = strIn + '<div id="categorySelDiv" >' + genCategrorySel(id) + '</div>';
    strIn = strIn + '</td><td width="5"><img src="images/spacer.gif" alt="" width="5" height="10" border="0" /></td>';
    strIn = strIn + '</tr></table><table width="100%" border="0" cellpadding="0" cellspacing="0" id="tableclose">';
    strIn = strIn + '<tr><td height="4" colspan="3"><img src="images/spacer.gif" alt="" width="8" height="4" border="0" /></td>';
    strIn = strIn + '</tr><tr><td width="8" height="10"><img src="images/spacer.gif" alt="" width="8" height="10" border="0" /></td>';
    strIn = strIn + '<td height="10" background="images/table_top_bg.gif"><img src="images/spacer.gif" alt="" width="8" height="10" border="0" /></td>';
    strIn = strIn + '<td width="5" height="10"><img src="images/spacer.gif" alt="" width="5" height="10" border="0" /></td>';
    
    strIn = strIn + '</tr></table><table width="100%" border="0" cellpadding="0" cellspacing="0" id="to"><tr>';
    strIn = strIn + '<td width="13" valign="top"><img src="images/spacer.gif" alt="" width="13" height="13" border="0" /></td><td>';
    strIn = strIn + '<div id="categoryResultDiv" style="height: ' + w_height_FT + 'px; width: 100%; overflow-x: hidden; overflow-y: auto;">';
    strIn = strIn + '<div id="divCate_0" style=" margin-right: 1px; display:inline;"></div><div id="divCate_1" style=" margin-right: 1px; display:inline;"></div><div id="divCate_2" style=" margin-right: 1px; display:inline;"></div><div id="divCate_3" style=" margin-right: 1px; display:inline;"></div><div id="divCate_4" style=" margin-right: 1px; display:inline;"></div><div id="divCate_5" style=" margin-right: 1px; display:inline;"></div>';
    strIn = strIn + '<div id="divCate_6" style=" margin-right: 1px; display:inline;"></div><div id="divCate_7" style=" margin-right: 1px; display:inline;"></div><div id="divCate_8" style=" margin-right: 1px; display:inline;"></div><div id="divCate_9" style=" margin-right: 1px; display:inline;"></div><div id="divCate_10" style=" margin-right: 1px; display:inline;"></div></div>';
    strIn = strIn + '</td><td width="5"><img src="images/spacer.gif" alt="" width="5" height="10" border="0" /></td>';
    strIn = strIn + '</tr></table><table width="100%" border="0" cellpadding="0" cellspacing="0" id="tableclose2">';
    strIn = strIn + '<tr><td height="4" colspan="3"><img src="images/spacer.gif" alt="" width="8" height="4" border="0" /></td>';
    strIn = strIn + '</tr><tr><td width="8" height="10"><img src="images/spacer.gif" alt="" width="8" height="10" border="0" /></td>';
    strIn = strIn + '<td height="10" background="images/table_top_bg.gif"><img src="images/spacer.gif" alt="" width="8" height="10" border="0" /></td>';
    strIn = strIn + '<td width="5" height="10"><img src="images/spacer.gif" alt="" width="5" height="10" border="0" /></td>';
    
    strIn = strIn + '</tr></table>';
    strIn = strIn + '<table width="100%" border="0" cellpadding="0" cellspacing="0"><tr>';
  strIn = strIn + '<td width="13" height="27" valign="top" ><img src="images/spacer.gif" alt="" width="13" height="13" border="0" /></td>';
  strIn = strIn + '<td width="55" height="27" valign="top" ><a href="#" onclick="backToCategory()">';
  if (lang=='E'){
        strIn = strIn + '<img src="images/back.gif" alt="" width="55" height="27" border="0" /></a></td>';
    }else if (lang=='TC'){
        strIn = strIn + '<img src="big5/images/back.gif" alt="" width="55" height="27" border="0" /></a></td>';
    }else if (lang=='SC'){
        strIn = strIn + '<img src="gb/images/back.gif" alt="" width="55" height="27" border="0" /></a></td>';
    }else{
        strIn = strIn + '<img src="images/back.gif" alt="" width="55" height="27" border="0" /></a></td>';
    }

  strIn = strIn + '<td width="1049" height="27" class="normalText"></td>';
  strIn = strIn + '<td width="5" valign="top" ><img src="images/spacer.gif" alt="" width="5" height="13" border="0" /></td>';
  strIn = strIn + '</tr></table></div>';
    ul.innerHTML = strIn;
    
}

function backToCategory(){
    var str = '<table width="100%" border="0" cellspacing="0" cellpadding="0"><tr>';
    str = str + '<td width="13" rowspan="4"><img src="images/spacer.gif" alt="" width="13" height="10" border="0" /></td>';
    str = str + '<td width="50%" height="5"><img src="images/spacer.gif" alt="" width="5" height="5" border="0" /></td>';
    str = str + '<td width="5" height="5"><img src="images/spacer.gif" alt="" width="5" height="5" border="0" /></td>';
    str = str + '<td width="50%" height="5"><img src="images/spacer.gif" alt="" width="5" height="5" border="0" /></td>';
    str = str + '<td width="5" rowspan="12"><img src="images/spacer.gif" alt="" width="5" height="10" border="0" /></td>';
    str = str + '</tr><tr>'
    str = str + genCategoryButtom(1,dispCategoryButtom1[langMod]);
  str = str + '<td width="5">&nbsp;</td>';
    str = str + genCategoryButtom(2,dispCategoryButtom2[langMod]);
  str = str + '</tr><tr>';
  str = str + '<td width="50%" height="5"><img src="images/spacer.gif" alt="" width="5" height="5" border="0" /></td>';
  str = str + '<td width="5" height="5"><img src="images/spacer.gif" alt="" width="5" height="5" border="0" /></td>';
  str = str + '<td width="50%" height="5"><img src="images/spacer.gif" alt="" width="5" height="5" border="0" /></td>';
  str = str + '</tr><tr>';
  str = str + genCategoryButtom(3,dispCategoryButtom3[langMod]);
    str = str + '<td width="5">&nbsp;</td>';
    str = str + genCategoryButtom(4,dispCategoryButtom4[langMod]);
    str = str + '</tr><tr>';
    str = str + '<td rowspan="6">&nbsp;</td>';
    str = str + '<td width="50%" height="5"><img src="images/spacer.gif" alt="" width="5" height="5" border="0" /></td>';
    str = str + '<td width="5" height="5"><img src="images/spacer.gif" alt="" width="5" height="5" border="0" /></td>';
    str = str + '<td width="50%" height="5"><img src="images/spacer.gif" alt="" width="5" height="5" border="0" /></td>';
    str = str + '</tr><tr>';
  str = str + genCategoryButtom(5,dispCategoryButtom5[langMod]);
    str = str + '<td>&nbsp;</td>';
  str = str + genCategoryButtom(6,dispCategoryButtom6[langMod]);
    str = str + '</tr><tr>';
    str = str + '<td width="50%" height="10"><img src="images/spacer.gif" alt="" width="10" height="10" border="0" /></td>';
  str = str + '<td width="5" height="5"><img src="images/spacer.gif" alt="" width="5" height="5" border="0" /></td>';
  str = str + '<td width="50%" height="10"><img src="images/spacer.gif" alt="" width="10" height="10" border="0" /></td>';
  str = str + '</tr></table>';
    str = str + '<table width="100%" border="0" cellspacing="0" cellpadding="0"><tr>';
  str = str + '<td width="13"><img src="images/spacer.gif" alt="" width="13" height="13" border="0" /></td>';
  str = str + '<td><span class="normalText">' + dispDescription[langMod] + ':</span><br /><br />';
  str = str + '<span class="normalText">' + dispDesc2[langMod] + '</span></td>';
  str = str + '<td width="5"><img src="images/spacer.gif" alt="" width="5" height="10" border="0" /></td>';
  str = str + '</tr></table>';
    TabHtml_2 = str;
    var s3_content=document.getElementById('s3_content');
    s3_content.innerHTML = TabHtml_2;
}

function genTabTitle(id, im){
    var strTitle = '<tr><td><table border="0" cellpadding="0" cellspacing="0" width="100%"><tr>';
    strTitle = strTitle + '<td width="10" height="14"><img name="btn_r1_c1" src="table/btn_small_left.gif" width="10" height="14" border="0" id="btn_r1_c5" alt=""></td>';
    strTitle = strTitle + '<td width="100%" height="14" nowrap="nowrap" bgcolor="#00AE8E"><a href="#" onclick="swithTab(' + id + ')" class="tableSmall">';
    if (lang=='E'){
        strTitle = strTitle + '<img src="images/' + im + '" border="0"></a></td>';
    }else if (lang=='TC'){
        strTitle = strTitle + '<img src="big5/images/' + im + '" border="0"></a></td>';
    }else if (lang=='SC'){
        strTitle = strTitle + '<img src="gb/images/' + im + '" border="0"></a></td>';
    }else{
        strTitle = strTitle + '<img src="images/' + im + '" border="0"></a></td>';
    }

    strTitle = strTitle + '<td width="10" height="14"><img name="btn_r1_c3" src="table/btn_small_right.gif" width="10" height="14" border="0" id="btn_r1_c6" alt=""></td>';
    strTitle = strTitle + '</tr></table></td></tr>';
    return strTitle;
}

function genCategoryButtom(id,mTitle){
    var str;
    str = '<td width="50%"><table border="0" cellpadding="0" cellspacing="0" width="100%"><tr>';
    str = str + '<td width="10" height="22"><img name="btn_r1_c1" src="table/btn_big_left.gif" width="10" height="22" border="0" id="btn_big_left4" alt="" /></td>';
    str = str + '<td width="100%" height="22" nowrap="nowrap" bgcolor="#00AE8E"><div align="center"><a href="#" onclick="swithCategory(' + id + ')" class="tableBig">' + mTitle + '</a></div></td>';
    str = str + '<td width="10" height="22"><img name="btn_r1_c3" src="table/btn_big_right.gif" width="10" height="22" border="0" id="btn_big_right4" alt="" /></td>';
    str = str + '</tr></table></td>';
    return str;
}

function genCategrorySel(id){
    var strSubCate = "arrSubCate_" + id;
    var strSubCateD = "arrSubCateD_" + id;
    
    var str='<table width="100%" border="0" cellpadding="0" cellspacing="0" id="from"><tr>';
    str = str + '<td width="13" valign="top"><img src="images/spacer.gif" alt="" width="13" height="13" border="0" /></td>';
    str = str + '<td><table width="100%" border="0" cellspacing="0" cellpadding="0"><tr>';
    str = str + '<td width="60" nowrap="nowrap"><div align="right"><strong class="normalPointText">' + dispCategory[langMod] + '</strong></div></td>';
    str = str + '<td width="5" rowspan="3" nowrap="nowrap"><img src="images/spacer.gif" alt="" width="5" height="5" border="0" /></td>';
    str = str + '<td ><select name="categoryNo" class="form-fields-small" id="categoryNo" style="width: 240px;" onchange="getCategory(true)">';
    for(var i=0; i < eval(strSubCate).length; i++){
        str = str + '<option value="' + eval(strSubCate)[i] + '">' + eval(strSubCateD)[langMod][i] + '</option>';
    }                                
    str = str + '</select></td>';
    str = str + '<td width="5" rowspan="3" ><img src="images/spacer.gif" alt="" width="5" height="5" border="0" /></td>';
    str = str + '</tr><tr>';
    str = str + '<td width="60" height="3" nowrap="nowrap"><img src="images/spacer.gif" alt="" width="3" height="3" border="0" /></td>';
    str = str + '<td height="3" ><img src="images/spacer.gif" alt="" width="3" height="3" border="0" /></td>';
    str = str + '</tr><tr>';
    str = str + '<td width="60" nowrap="nowrap"><div align="right"><strong class="normalPointText">' + dispDistricts[langMod] + '</strong></div></td>';
    str = str + '<td ><select name="districtNo" class="form-fields-small" id="districtNo" style="width: 240px;" onchange="getCategory(true)">';
    for(var i=0; i < arrDistrict.length; i++){
        str = str + '<option value="' + arrDistrict[i] + '">' + arrDistrictD[langMod][i] + '</option>';
    }  
    str = str + '</select></td></tr><tr>';
    str = str + '<td height="3" colspan="4"><span class="normalText"><img src="images/spacer.gif" alt="" width="5" height="3" border="0" /></span></td>';
    str = str + '</tr></table></td>';
    str = str + '<td width="5"><img src="images/spacer.gif" alt="" width="5" height="10" border="0" /></td>';
    str = str + '</tr></table>';

    return str;
}

//supermap parameter
var drssReturnPathInfoParam;
var drssRouteParam0 = null;

//supermap function
function getSP(nodeID){
    for (var i=0; i<6; i ++){
        if (nodeID == crossingList[i][0]){
            getSPM(crossingList[i][1],crossingList[i][2]);
            return;
        }   
    }
    
    /*if (e("criteria3").checked){
        getSP0(edgeID, "STS");      //Shortest Travel Time (Static)
    }else*/ if (e("criteria1").checked){
        getSP0(nodeID, "SD");//Shortest Distance    
    }else if (e("criteria4").checked){
        getSP0(nodeID, "STR");  //Shortest Travel Time (Real Time)
    }else if (e("criteria2").checked){
        getSP0(nodeID, "CT");   //Cheapest tunnel/bridge toll
    }else {
        alert ("Please select Shortest Distance!");
        return; 
    }
}

function getSPM(xMid,yMid){
    /*if (e("criteria3").checked){
        getSP0(0, "STS",xMid,yMid);     //Shortest Travel Time (Static)
    }else*/ if (e("criteria1").checked){
        getSP0(0, "SD",xMid,yMid);//Shortest Distance   
    }else if (e("criteria4").checked){
        getSP0(0, "STR",xMid,yMid); //Shortest Travel Time (Real Time)
    }else if (e("criteria2").checked){
        getSP0(0, "CT",xMid,yMid);  //Cheapest tunnel/bridge toll
    }else {
        alert ("Please select Shortest Distance!");
        return; 
    }
}

function getSP0(nodeID, iType, xMid, yMid){
    /*
    ***nodeID***
    block node id

    ***iType*** 
    "SD": Shortest Distance     (FTcost,TFcost)
    "CT": Cheapest tunnel/bridge toll   (FTcostToll,TFcostToll)
    "STS": Shortest Travel Time (Static)    (FTcostST, TFcostST)
    "STR": Shortest Travel Time (Real Time)  (FTcostRT, TFcostRT)
    
    ******
    */

    time4 = getTimeNow();
    
if (gSkipInt>0){
    if (gSkipInt != 2){
        //Henry
        alert (alertAvoid3[langMod]);
        hideLoading();
        return; 
    }   
}
if (onlineCount>200){
    if (lang=='E'){
        alert ('Server Busy. Please try again later.');
    }else if (lang=='TC'){
        alert ('伺服器繁忙中, 請遲些再試.');
    }else if (lang=='SC'){
        alert ('伺服器繁忙中, 请迟些再试.');
    }else{
        alert ('Server Busy. Please try again later.');
    }
    hideLoading();
}else{
    time5 = getTimeNow();
    showLoading();
    var strFTcost, strTFcost;
    switch (iType) {
    case "SD":
            strFTcost = "FTcost";
      strTFcost = "TFcost";
      break;
    case "CT":
            strFTcost = "FTcostToll";
      strTFcost = "TFcostToll";
      break;
    case "STS" :
            strFTcost = "FTcostST";
      strTFcost = "TFcostST";
      break;
    case "STR" :
            strFTcost = "FTcostRT";
      strTFcost = "TFcostRT";
      break;
   default :
      strFTcost = "FTcostST";
      strTFcost = "TFcostST";
    } 


    var barrierNodes=new Array();
    if (nodeID==0){

        barrierNodes.push(0);
    }else{ //avoid road

        var avoidArr=new Array();
        avoidArr = nodeID.split(",");
        for (var i=0; i<avoidArr.length; i++){
            barrierNodes.push(avoidArr[i]);
        }
    }
    var skipFrom;
    var skipTo;
    var skipTemp
    if (gSkipInt == 2){
        for(var i=0; i<gAllNode.length; i++){
            if (gAllNode[i] == gSkipNode[0]){
                skipFrom = i;   
            }
            if (gAllNode[i] == gSkipNode[1]){
                skipTo = i; 
            }
        }
        if (skipFrom>skipTo){
            skipTemp = skipFrom;
            skipFrom = skipTo;
            skipTo = skipTemp;
        }
        skipTo++;
        
        for(var i=skipFrom; i<skipTo; i++){

            barrierNodes.push(gAllNode[i]);
        }
        //fixed for issue(20121218 mail from Eric)
        if (barrierNodes.length < 2){
            barrierNodes.push(gSkipNode[0]);
            barrierNodes.push(gSkipNode[1]);
        }
    }
    //if (!drssRouteParam0){
        drssRouteParam0=new SuperMap.IS.RouteParam();
        drssRouteParam0.networkParams=new SuperMap.IS.NetworkParams();
        drssRouteParam0.networkParams.networkSetting=new SuperMap.IS.NetworkSetting();
        drssRouteParam0.networkParams.networkSetting.edgeIDField="SmID";
        drssRouteParam0.networkParams.networkSetting.nodeIDField="SmNodeID";
        drssRouteParam0.networkParams.networkSetting.networkLayerName="NetDT@hk";
        drssRouteParam0.networkParams.networkSetting.FTWeightField=strFTcost;
        drssRouteParam0.networkParams.networkSetting.TFWeightField=strTFcost;
        drssRouteParam0.networkParams.networkSetting.barrierNodes=barrierNodes;
        drssRouteParam0.networkParams.tolerance=0.01;
        
        //turning table
        drssRouteParam0.networkParams.turnTableSetting=new SuperMap.IS.TurnTableSetting();
        drssRouteParam0.networkParams.turnTableSetting.fromEdgeIDField ="FEdgeID";
        drssRouteParam0.networkParams.turnTableSetting.nodeIDField ="NodeID";
        drssRouteParam0.networkParams.turnTableSetting.toEdgeIDField ="TEdgeID";  
        drssRouteParam0.networkParams.turnTableSetting.weightField = "TurnCost";
        drssRouteParam0.networkParams.turnTableSetting.turnTableName = "TRN@hk";
        
        drssRouteParam0.returnEdgeIDsAndNodeIDs=true;
        drssRouteParam0.returnNodePositions=true;
        
        drssReturnPathInfoParam = new SuperMap.IS.ReturnPathInfoParam();
        if (lang == 'E'){
            drssReturnPathInfoParam.edgeNameField = "RouteInfo_E";
            drssReturnPathInfoParam.nodeNameField = "NodeInfo_E";
        }else if (lang == 'TC'){
            drssReturnPathInfoParam.edgeNameField = "RouteInfo_TC";
            drssReturnPathInfoParam.nodeNameField = "NodeInfo_tc";
        }else if (lang == 'SC'){
            drssReturnPathInfoParam.edgeNameField = "RouteInfo_TC";
            drssReturnPathInfoParam.nodeNameField = "NodeInfo_tc";
        }else{
            drssReturnPathInfoParam.edgeNameField = "RouteInfo_E";
            drssReturnPathInfoParam.nodeNameField = "NodeInfo_E";
        }
        //drssReturnPathInfoParam.returnPathTable = true;
        drssReturnPathInfoParam.returnPathGuide = true;
        drssRouteParam0.returnPathInfo=drssReturnPathInfoParam; 
        //no highlight no new map request
        drssRouteParam0.highlight = new SuperMap.IS.Highlight();
    drssRouteParam0.highlight.highlightResult = false;
    //}
        


    var keyPoints=new Array();
    if(xMid == void 0){





        keyPoints.push(new SuperMap.IS.MapCoord(fromLon,fromLat));





        if (gIncludeInt > 0){
            for (var i=0; i<gIncludeInt; i++){
                keyPoints.push(new SuperMap.IS.MapCoord(gIncludeLon[i],gIncludeLat[i]));
            }
        }




        keyPoints.push(new SuperMap.IS.MapCoord(toLon,toLat));




    }else{

        keyPoints.push(new SuperMap.IS.MapCoord(fromLon,fromLat));
        keyPoints.push(new SuperMap.IS.MapCoord(xMid,yMid));
        keyPoints.push(new SuperMap.IS.MapCoord(toLon,toLat));  
    }
    

    
    /*
        fn - iType;
        qt - datetime.now
        olon - fromLon
        olan - fromLat
        oloc - e("from").value
        dlon - toLon
        dlan - toLat
        dloc - e("to").value
        ipc - gIncludeInt
        apc - gSkipInt
    */
    try{
        //update_query_record(iType,fromLon,fromLat,e("from").value,toLon,toLat,e("to").value,gIncludeInt,gSkipInt);
    }
    catch(err_log){
    }

        time6 = getTimeNow();
    switch (iType) {
    case "SD":
            //smMap1.GetSpatialAnalystManager().FindPathByPoints (keyPoints,drssRouteParam0,onComplete ,onError, iType );
            var mapHandler = "http://203.194.149.169/drss1/AjaxScripts/";
            var mapName = "hk1";
            tFindPathByPoints(mapHandler, mapName, keyPoints,drssRouteParam0,onComplete ,onError, iType );
      break;
    case "CT":
            //smMap2.GetSpatialAnalystManager().FindPathByPoints (keyPoints,drssRouteParam0,onComplete ,onError, iType );
            var mapHandler = "http://203.194.149.169/drss2/AjaxScripts/";
            var mapName = "hk2";
            tFindPathByPoints(mapHandler, mapName, keyPoints,drssRouteParam0,onComplete ,onError, iType );
      break;
//    case "STS" :
//          smMap3.GetSpatialAnalystManager().FindPathByPoints (keyPoints,drssRouteParam0,onComplete ,onError, iType );
//      break;
    case "STR" :
            //smMap4.GetSpatialAnalystManager().FindPathByPoints (keyPoints,drssRouteParam0,onComplete ,onError, iType );
            var mapHandler = "http://203.194.149.169/drss4/AjaxScripts/";
            var mapName = "hk";
            tFindPathByPoints(mapHandler, mapName, keyPoints,drssRouteParam0,onComplete ,onError, iType );
      break;
   default :
      //smMap1.GetSpatialAnalystManager().FindPathByPoints (keyPoints,drssRouteParam0,onComplete ,onError, iType );
      var mapHandler = "http://203.194.149.169/drss1/AjaxScripts/";
            var mapName = "hk1";
            tFindPathByPoints(mapHandler, mapName, keyPoints,drssRouteParam0,onComplete ,onError, iType );
    } 
    //smMap.GetSpatialAnalystManager().FindPathByPoints (keyPoints,drssRouteParam0,onComplete ,onError, iType );
}   
}

// Nelson Leung

function update_query_record(fn,olon,olat,oloc,dlon,dlat,dloc,ipc,apc){
    
    return;
    
    try{




        var update_url = "http://203.194.149.169/drss/save_drss_log.php";
        update_url += "?fn=" + fn;
        update_url += "&qt=" + get_current_time();
        update_url += "&olon=" + olon;
        update_url += "&olat=" + olat;
        update_url += "&oloc=" + encodeURIComponent(oloc);
        update_url += "&dlon=" + dlon;
        update_url += "&dlat=" + dlat;
        update_url += "&dloc=" + encodeURIComponent(dloc);
        update_url += "&ipc=" + ipc;
        update_url += "&apc=" + apc;

    





        var XMLHttpRequestObject;
        if (window.XMLHttpRequest)
        {
            XMLHttpRequestObject = new XMLHttpRequest();
        }
        else if (window.ActiveXObject)
        {
            XMLHttpRequestObject = new ActiveXObject("Microsoft.XMLHTTP");
        }
        
        
        if(XMLHttpRequestObject)
        {
            XMLHttpRequestObject.onreadystatechange = function(){}
            XMLHttpRequestObject.open("post", update_url);
            XMLHttpRequestObject.send(null);
        }
        
    }
    catch(err){
        //alert(err.description);
    }

}

function get_current_time(){

    try{
    
        var current_time = new Date();
        var current_time_str = '';
        
        current_time_str += current_time.getFullYear() + '-';
        
        if( ( current_time.getMonth() + 1 ) < 10){
            current_time_str += '0' + ( current_time.getMonth() + 1 ) + '-';
        }
        else{
            current_time_str += ( current_time.getMonth() + 1 ) + '-';
        }
        
        if( current_time.getDate() < 10){
            current_time_str += '0' + current_time.getDate() + '%20';
        }
        else{
            current_time_str += current_time.getDate() + '%20';
        }
        
        if( current_time.getHours() < 10){
            current_time_str += '0' + current_time.getHours() + ':';
        }
        else{
            current_time_str += current_time.getHours() + ':';
        }
        
        if( current_time.getMinutes() < 10){
            current_time_str += '0' + current_time.getMinutes() + ':';
        }
        else{
            current_time_str += current_time.getMinutes() + ':';
        }
        
        if( current_time.getSeconds() < 10){
            current_time_str += '0' + current_time.getSeconds() + '.';
        }
        else{
            current_time_str += current_time.getSeconds() + '.';
        }
        
        if( current_time.getMilliseconds() < 10 ){
            current_time_str += '00' + current_time.getMilliseconds() + '';
        }
        else if( current_time.getMilliseconds() < 100 ){
            current_time_str += '0' + current_time.getMilliseconds() + '';
        }
        else{
            current_time_str += current_time.getMilliseconds() + '';
        }
        
        return current_time_str;
    }
    catch(err){}
}

// Nelson Leung




function getSP2(nodeID, iType){

    // alert("getSP2");
    var harbID1, harbID2;
    var harbLon1, harbLon2, harbLat1, harbLat2;
    var strFTcost, strTFcost;
    var userContext1, userContext2;
    
    userContext1 = "1" + iType;
    userContext2 = "2" + iType;
    


    switch (iType) {
    case "SD" :
            strFTcost = "FTcost";
      strTFcost = "TFcost";
      break;
    case "CT" :
            strFTcost = "FTcostToll";
      strTFcost = "TFcostToll";
      break;
    case "STS" :
            strFTcost = "FTcostST";
      strTFcost = "TFcostST";
      break;
    case "STR" :
            strFTcost = "FTcostRT";
      strTFcost = "TFcostRT";
      break;
   default :
      strFTcost = "FTcostST";
      strTFcost = "TFcostST";
    } 
    //alert(nodeID);
    if (nodeID==0) return;

    var divIMG = document.getElementById('pathIMG');
    while(divIMG.hasChildNodes()){
        divIMG.removeChild(divIMG.firstChild);
    }
    divIMG.style.display="block";
    var myIMG=document.createElement('img');

    if (nodeID == crossingList[0][0]){
        harbID1=crossingList[1][0];
        harbLon1=crossingList[1][1];
        harbLat1=crossingList[1][2];
        harbID2=crossingList[2][0];
        harbLon2=crossingList[2][1];
        harbLat2=crossingList[2][2];
        if (lang=='E')
        {
            myIMG.src="images/CHT.jpg";
        }else{
            myIMG.src="images/CHT_C.jpg";
        }

    }
    if (nodeID == crossingList[1][0]){
        harbID1=crossingList[0][0];
        harbLon1=crossingList[0][1];
        harbLat1=crossingList[0][2];
        harbID2=crossingList[2][0];
        harbLon2=crossingList[2][1];
        harbLat2=crossingList[2][2];
        if (lang=='E')
        {
            myIMG.src="images/WHC.jpg";
        }else{
            myIMG.src="images/WHC_C.jpg";
        }

    }
    if (nodeID == crossingList[2][0]){
        harbID1=crossingList[0][0];
        harbLon1=crossingList[0][1];
        harbLat1=crossingList[0][2];
        harbID2=crossingList[1][0];
        harbLon2=crossingList[1][1];
        harbLat2=crossingList[1][2];
        if (lang=='E')
        {
            myIMG.src="images/EHC.jpg";
        }else{
            myIMG.src="images/EHC_C.jpg";
        }

    }
    if (nodeID == crossingList[3][0]){
        harbID1=crossingList[4][0];
        harbLon1=crossingList[4][1];
        harbLat1=crossingList[4][2];
        harbID2=crossingList[5][0];
        harbLon2=crossingList[5][1];
        harbLat2=crossingList[5][2];
        if (lang=='E')
        {
            myIMG.src="images/CHT.jpg";
        }else{
            myIMG.src="images/CHT_C.jpg";
        }
    }
    if (nodeID == crossingList[4][0]){
        harbID1=crossingList[3][0];
        harbLon1=crossingList[3][1];
        harbLat1=crossingList[3][2];
        harbID2=crossingList[5][0];
        harbLon2=crossingList[5][1];
        harbLat2=crossingList[5][2];
        if (lang=='E')
        {
            myIMG.src="images/WHC.jpg";
        }else{
            myIMG.src="images/WHC_C.jpg";
        }
    }
    if (nodeID == crossingList[5][0]){
        harbID1=crossingList[3][0];
        harbLon1=crossingList[3][1];
        harbLat1=crossingList[3][2];
        harbID2=crossingList[4][0];
        harbLon2=crossingList[4][1];
        harbLat2=crossingList[4][2];
        if (lang=='E')
        {
            myIMG.src="images/EHC.jpg";
        }else{
            myIMG.src="images/EHC_C.jpg";
        }
    }
    
    myIMG.id="myIMG";
    myIMG.setAttribute('height', '40px');
    myIMG.setAttribute('width', '44px');
    divIMG.appendChild(myIMG)
    
    //NO 1
    var harbRouteParam=new SuperMap.IS.RouteParam();
    harbRouteParam.networkParams=new SuperMap.IS.NetworkParams();
    harbRouteParam.networkParams.networkSetting=new SuperMap.IS.NetworkSetting();
    harbRouteParam.networkParams.networkSetting.edgeIDField="SmID";
    harbRouteParam.networkParams.networkSetting.nodeIDField="SmNodeID";
    harbRouteParam.networkParams.networkSetting.networkLayerName="NetDT@hk";
    harbRouteParam.networkParams.networkSetting.FTWeightField=strFTcost;
    harbRouteParam.networkParams.networkSetting.TFWeightField=strTFcost;
    //harbRouteParam.networkParams.networkSetting.barrierNodes=barrierNodes;
    harbRouteParam.networkParams.tolerance=0.01;
    //turning table
    harbRouteParam.networkParams.turnTableSetting=new SuperMap.IS.TurnTableSetting();
    harbRouteParam.networkParams.turnTableSetting.fromEdgeIDField ="FEdgeID";
    harbRouteParam.networkParams.turnTableSetting.nodeIDField ="NodeID";
    harbRouteParam.networkParams.turnTableSetting.toEdgeIDField ="TEdgeID";  
    harbRouteParam.networkParams.turnTableSetting.weightField = "TurnCost";
    harbRouteParam.networkParams.turnTableSetting.turnTableName = "TRN@hk";
    
    harbRouteParam.returnEdgeIDsAndNodeIDs=false;
    harbRouteParam.returnNodePositions=false;
    
    drssReturnPathInfoParam = new SuperMap.IS.ReturnPathInfoParam();
    if (lang == 'E'){
        drssReturnPathInfoParam.edgeNameField = "RouteInfo_E";
        drssReturnPathInfoParam.nodeNameField = "NodeInfo_E";
    }else if (lang == 'TC'){
        drssReturnPathInfoParam.edgeNameField = "RouteInfo_TC";
        drssReturnPathInfoParam.nodeNameField = "NodeInfo_tc";
    }else if (lang == 'SC'){
        drssReturnPathInfoParam.edgeNameField = "RouteInfo_TC";
        drssReturnPathInfoParam.nodeNameField = "NodeInfo_tc";
    }else{
        drssReturnPathInfoParam.edgeNameField = "RouteInfo_E";
        drssReturnPathInfoParam.nodeNameField = "NodeInfo_E";
    }
    //drssReturnPathInfoParam.returnPathTable = true;
    drssReturnPathInfoParam.returnPathGuide = true;
    harbRouteParam.returnPathInfo=drssReturnPathInfoParam; 
    //no highlight no new map request
    harbRouteParam.highlight = new SuperMap.IS.Highlight();
  harbRouteParam.highlight.highlightResult = false;
        
    var keyPoints=new Array();
    keyPoints.push(new SuperMap.IS.MapCoord(fromLon,fromLat));
    keyPoints.push(new SuperMap.IS.MapCoord(harbLon1,harbLat1));
    keyPoints.push(new SuperMap.IS.MapCoord(toLon,toLat));

    // alert("getSP2-01");
    switch (iType) {
    case "SD":
            //smMap1.GetSpatialAnalystManager().FindPathByPoints (keyPoints,harbRouteParam,onComplete2 ,onError2, userContext1 );
            var mapHandler = "http://203.194.149.169/drss1/AjaxScripts/";
            var mapName = "hk1";
            tFindPathByPoints(mapHandler, mapName, keyPoints,harbRouteParam,onComplete2 ,onError2, userContext1 );
      break;
    case "CT":
            //smMap2.GetSpatialAnalystManager().FindPathByPoints (keyPoints,harbRouteParam,onComplete2 ,onError2, userContext1 );
            var mapHandler = "http://203.194.149.169/drss2/AjaxScripts/";
            var mapName = "hk2";
            tFindPathByPoints(mapHandler, mapName, keyPoints,harbRouteParam,onComplete2 ,onError2, userContext1 );
      break;
//    case "STS" :
//          smMap3.GetSpatialAnalystManager().FindPathByPoints (keyPoints,harbRouteParam,onComplete2 ,onError2, userContext1 );
//      break;
    case "STR" :
            //smMap4.GetSpatialAnalystManager().FindPathByPoints (keyPoints,harbRouteParam,onComplete2 ,onError2, userContext1 );
            var mapHandler = "http://203.194.149.169/drss4/AjaxScripts/";
            var mapName = "hk";
            tFindPathByPoints(mapHandler, mapName, keyPoints,harbRouteParam,onComplete2 ,onError2, userContext1 );
      break;
   default :
      //smMap1.GetSpatialAnalystManager().FindPathByPoints (keyPoints,harbRouteParam,onComplete2 ,onError2, userContext1 );
      var mapHandler = "http://203.194.149.169/drss1/AjaxScripts/";
            var mapName = "hk1";
            tFindPathByPoints(mapHandler, mapName, keyPoints,harbRouteParam,onComplete2 ,onError2, userContext1 );
    } 
    // alert("getSP2-01 sent");
    //smMap.GetSpatialAnalystManager().FindPathByPoints (keyPoints,harbRouteParam,onComplete2 ,onError2, userContext1 );

    //NO 2
    harbRouteParam=new SuperMap.IS.RouteParam();
    harbRouteParam.networkParams=new SuperMap.IS.NetworkParams();
    harbRouteParam.networkParams.networkSetting=new SuperMap.IS.NetworkSetting();
    harbRouteParam.networkParams.networkSetting.edgeIDField="SmID";
    harbRouteParam.networkParams.networkSetting.nodeIDField="SmNodeID";
    harbRouteParam.networkParams.networkSetting.networkLayerName="NetDT@hk";
    harbRouteParam.networkParams.networkSetting.FTWeightField=strFTcost;
    harbRouteParam.networkParams.networkSetting.TFWeightField=strTFcost;
    //harbRouteParam.networkParams.networkSetting.barrierNodes=barrierNodes;
    harbRouteParam.networkParams.tolerance=0.01;
    //turning table
    harbRouteParam.networkParams.turnTableSetting=new SuperMap.IS.TurnTableSetting();
    harbRouteParam.networkParams.turnTableSetting.fromEdgeIDField ="FEdgeID";
    harbRouteParam.networkParams.turnTableSetting.nodeIDField ="NodeID";
    harbRouteParam.networkParams.turnTableSetting.toEdgeIDField ="TEdgeID";  
    harbRouteParam.networkParams.turnTableSetting.weightField = "TurnCost";
    harbRouteParam.networkParams.turnTableSetting.turnTableName = "TRN@hk";
    
    harbRouteParam.returnEdgeIDsAndNodeIDs=false;
    harbRouteParam.returnNodePositions=false;
    
    harbRouteParam.returnPathInfo=drssReturnPathInfoParam; 
    //no highlight no new map request
    harbRouteParam.highlight = new SuperMap.IS.Highlight();
  harbRouteParam.highlight.highlightResult = false;
  
    keyPoints=new Array();
    keyPoints.push(new SuperMap.IS.MapCoord(fromLon,fromLat));
    keyPoints.push(new SuperMap.IS.MapCoord(harbLon2,harbLat2));
    keyPoints.push(new SuperMap.IS.MapCoord(toLon,toLat));
    // alert("getSP2-02");
    switch (iType) {
    case "SD":
            //smMap1.GetSpatialAnalystManager().FindPathByPoints (keyPoints,harbRouteParam,onComplete2 ,onError2, userContext2 );
            var mapHandler = "http://203.194.149.169/drss1/AjaxScripts/";
            var mapName = "hk1";
            tFindPathByPoints(mapHandler, mapName, keyPoints,harbRouteParam,onComplete2 ,onError2, userContext2 );
      break;
    case "CT":
            //smMap2.GetSpatialAnalystManager().FindPathByPoints (keyPoints,harbRouteParam,onComplete2 ,onError2, userContext2 );
            var mapHandler = "http://203.194.149.169/drss2/AjaxScripts/";
            var mapName = "hk2";
            tFindPathByPoints(mapHandler, mapName, keyPoints,harbRouteParam,onComplete2 ,onError2, userContext2 );
      break;
//    case "STS" :
//          smMap3.GetSpatialAnalystManager().FindPathByPoints (keyPoints,harbRouteParam,onComplete2 ,onError2, userContext2 );
//      break;
    case "STR" :
            //smMap4.GetSpatialAnalystManager().FindPathByPoints (keyPoints,harbRouteParam,onComplete2 ,onError2, userContext2 );
            var mapHandler = "http://203.194.149.169/drss4/AjaxScripts/";
            var mapName = "hk";
            tFindPathByPoints(mapHandler, mapName, keyPoints,harbRouteParam,onComplete2 ,onError2, userContext2 );
      break;
   default :
      //smMap1.GetSpatialAnalystManager().FindPathByPoints (keyPoints,harbRouteParam,onComplete2 ,onError2, userContext2 );
      var mapHandler = "http://203.194.149.169/drss1/AjaxScripts/";
            var mapName = "hk1";
            tFindPathByPoints(mapHandler, mapName, keyPoints,harbRouteParam,onComplete2 ,onError2, userContext2 );
    }
    // alert("getSP2-02 sent");
    //smMap.GetSpatialAnalystManager().FindPathByPoints (keyPoints,harbRouteParam,onComplete2 ,onError2, userContext2 );

}

function tFindPathByPoints(mapHandler, mapName, points, routeParam, onComplete, onError, userContext) {

//time7 = getTimeNow();
    // alert("tFindPathByPoints");
    var _trackingLayerIndex = -1; 
    var _userID = "";



    if (points != null) {
        //alert("tFindPathByPoints - here");
        tFindPathBase(mapHandler, mapName, "FindPathByPoints", ["points", "routeParam", "trackingLayerIndex", "userID"], [points, routeParam, _trackingLayerIndex, _userID], onComplete, onError, userContext)
        //alert("tFindPathByPoints - sent");
    }
}

function tFindPathBase(mapHandler, mapName, methodName, paramNames, paramValues, onComplete, onError, userContext) {



    var queryUrl = mapHandler + "path.ashx";
    function onRequestComplete(responseText) {


        if (!responseText) {
            if (onComplete) { onComplete(null, userContext) }
            return

        }

        time10 = getTimeNow();


        var routeResultJ = eval("(" + responseText + ")");
        time11 = getTimeNow();
        
        var routeResult = new SuperMap.IS.RouteResult();
        routeResult.FromJSON(routeResultJ);
        time12 = getTimeNow();
        //_ChangeTrackingLayerKeyInternal(routeResult.trackingLayerIndex, routeResult.userID, true);
        if (onComplete) { onComplete(routeResult, userContext) }
        if (routeResultJ && routeResultJ.nodePositions) {
            while (routeResultJ.nodePositions.length > 0) { routeResultJ.nodePositions.pop() }
        }
        routeResultJ = null;
        routeResult.Destroy(); 
        routeResult = null


    }

    //alert("sent");
//alert(time8);
if(time9==null){
time8 = getTimeNow();
}
    var reuqestManager = new SuperMap.IS.RequestManager(queryUrl, onRequestComplete, onError, userContext);
    reuqestManager.AddQueryString("map", mapName);
    reuqestManager.AddQueryString("method", methodName);
    reuqestManager.AddQueryStrings(paramNames, paramValues);
    reuqestManager.Send();
    reuqestManager.Destroy();
    reuqestManager = null;
    while (paramNames.length > 0) { paramNames.pop(); paramValues.pop() }
    paramNames = null;
    paramValues = null
    if(time9==null){
time9 = getTimeNow();
}
}

//winsen 2010.2.3
function OpenChildWindow(URL, parameters, left, top, width, height, isModal)
{
    var str = "directories=no," +
  "location=no,menubar=no," +
  "resizable=no,status=no,toolbar=no," +
  "scrollbars=no,";
  str += "height="+height;
  str += ",";
  str += "width="+width;
  str += ",";
  var screenw = screen.width;
  var screenh = screen.height;
//  var left = (screenw - width)/2;
//  var top = (screenh - height)/2;
  str += "left=" + left;
  str += ",";
  str += "top=" + top;
    
    if(isModal)
    {
        window.showModalDialog(URL, parameters);
    }
    else
    {
        //window.showModelessDialog(URL, parameters);
        window.parameters = parameters;
        var child;
        child = window.open(URL, "", str);
        if (child != null)
        {
            child.focus();
        }
    }
}

function ShowWin(id, left, top, width, height, title, content)
{
    var str = 
        '<DIV id="" style="margin-top:5px; margin-right:5px; margin-bottom:5px; margin-left:5px;">'
        + '<DIV style="width:100%;">'
            + '<TABLE width="100%" align="center" cellspacing="0" cellpadding="0" border="0">' 
                + '<TBODY>'
                    + '<TR height="17"><TD valign="top" align="left" class="normalText">' + title + '</TD><TD width="14" valign="top" align="right"><img title='+resource_hide+' alt='+resource_hide+' style="height:13px" src="./images/hide.gif" onclick="closeWindow(e(\'' + id + '\'))"></TD></tr>'
                + '</TBODY>'
            + '</TABLE>' 
        + '</DIV>'
    + '</DIV>';
    
    str += content;
    
    var e = new xWin(id, left, top, width, height, 1, id, str);
}

function DeleteRepeatElement(arr){
    var resultArray = new Array();
    arr = arr.sort();
    
    for(var i = 0; i < arr.length; i++)
    {
        var temp = arr[i];
        while(arr[i] == temp && i < arr.length)
        {
            i++;
        }
        if(temp != "")
        {
            resultArray.push(temp);
        }
    }
    return resultArray;
}

function MergeAndSplit(arr, separator){
    var str = "";
    for(var i = 0; i < arr.length; i++)
    {
        str += arr[i];
    }
    
    return str.split(separator);
}

//winsen 2010.2.3
function onComplete (routeResult, userContext){

    time13 = getTimeNow();
    // Nelson debug
    var debug_content = '';
    
    var uat_textual = '';
    var uat_map = '';
    var uat_map_lat_lon = '';
    
    var str="";
    var nodeHarbour = 0;
    var strDistance = 0;
    var arrPosition = new Array();  // string , ['114.123456,22.123456','...,...']
    var realNode = new Array(); // name,x,y
    var realEdge =new Array();  //name,...
    
    if(!routeResult||!routeResult.edgeIDs||!routeResult.edgeIDs.length) //Cannot get the routing result
    //||!routeResult.nodeIDs||!routeResult.nodeIDs.length
    {
        hideLoading();
        if (lang == 'E'){
            str ="<div style='font-size:12px'>&nbsp;&nbsp;&nbsp;&nbsp;Route can not be found from (" + fromLon + "," + fromLat + ") to (" + toLon + "," + toLat + ").<br>&nbsp;&nbsp;<a href='#' onclick='goBack()'>"
            + "<img src='images/back.gif' alt='' width='55' height='27' border='0' /></a></div>";
        }else if (lang == 'TC'){
            str ="<div style='font-size:12px'>&nbsp;&nbsp;&nbsp;&nbsp;沒有適合路線由 (" + fromLon + "," + fromLat + ") 至 (" + toLon + "," + toLat + ").<br>&nbsp;&nbsp;<a href='#' onclick='goBack()'>"
            + "<img src='images/back.gif' alt='' width='55' height='27' border='0' /></a></div>";
        }else if (lang == 'SC'){
            str ="<div style='font-size:12px'>&nbsp;&nbsp;&nbsp;&nbsp;没有适合路线由 (" + fromLon + "," + fromLat + ") 至 (" + toLon + "," + toLat + ").<br>&nbsp;&nbsp;<a href='#' onclick='goBack()'>"
            + "<img src='images/back.gif' alt='' width='55' height='27' border='0' /></a></div>";
        }else{
            str ="<div style='font-size:12px'>&nbsp;&nbsp;&nbsp;&nbsp;Route can not be found from (" + fromLon + "," + fromLat + ") to (" + toLon + "," + toLat + ").<br>&nbsp;&nbsp;<a href='#' onclick='goBack()'>"
            + "<img src='images/back.gif' alt='' width='55' height='27' border='0' /></a></div>";
        }
        //doing
        var s3_content=document.getElementById('s3_content');
        s3_content.innerHTML = str; 
        return;
    }
    if (routeResult.nodeIDs){      // Check the cross harbour
        for (var i=0; i<routeResult.nodeIDs.length; i++){
            for (var j=0; j<6; j++){  //Crossing List at Category.js
                if(routeResult.nodeIDs[i]==crossingList[j][0]){
                    nodeHarbour = crossingList[j][0];
                    break;
                }
            }
            if (nodeHarbour>0){
                break;  
            }
        }
    }
//alert (routeResult.pathGuides[0].pathGuideItems.length);
//alert (routeResult.pathGuides[0].count);
    time14 = getTimeNow();
    if(routeResult.totalLength>0){
      
      var n_end_node_lat = 0;
      var n_end_node_lon = 0;
      
      if(routeResult.nodePositions && routeResult.pathGuides){
      
        var node_index = 0;
        var segment_index = 1;
        
        for(var i=0 ; i<routeResult.pathGuides[0].pathGuideItems.length; i++){
            
            if(routeResult.pathGuides[0].pathGuideItems[i].isEdge == false){
            
                if(i+2 < routeResult.pathGuides[0].pathGuideItems.length){
                
                    var segment_end_lat = routeResult.pathGuides[0].pathGuideItems[i+2].bounds.rightTop.y.toFixed(6);
                    var segment_end_lon = routeResult.pathGuides[0].pathGuideItems[i+2].bounds.rightTop.x.toFixed(6);
                    
                    uat_map_lat_lon += routeResult.pathGuides[0].pathGuideItems[i+2].bounds.rightTop.y.toFixed(6) + ',' + routeResult.pathGuides[0].pathGuideItems[i+2].bounds.rightTop.x.toFixed(6) + ',' + segment_index + '\n';
                                        
                    while(node_index < routeResult.nodePositions.length){
                        
                        uat_map += routeResult.nodePositions[node_index].y.toFixed(6) + ',' + routeResult.nodePositions[node_index].x.toFixed(6) + ',' + segment_index + '\n';
                        node_index++;
                        if(segment_end_lat == routeResult.nodePositions[node_index-1].y.toFixed(6) && segment_end_lon == routeResult.nodePositions[node_index-1].x.toFixed(6)){break;}
                        
                        //alert(segment_end_lat + ',' + segment_end_lon + '\n' + routeResult.nodePositions[node_index-1].y.toFixed(6) + ',' + routeResult.nodePositions[node_index-1].x.toFixed(6));
                        
                    }
                    segment_index++;
                }
            }
            else{
                uat_textual += routeResult.pathGuides[0].pathGuideItems[i].name + ',' + routeResult.pathGuides[0].pathGuideItems[i-1].turnType + ',' + routeResult.pathGuides[0].pathGuideItems[i].id + '\n';
            }
            
        }
        
      }
      
      OpenWindowForText(uat_textual,'uat_textual01');
      OpenWindowForText(uat_map,'uat_map01');
      OpenWindowForText(uat_map_lat_lon,'uat_map_lat_lon_01');
      
      if(routeResult.nodePositions){ // Store the lat long to the array arrPosition
        for (var i=0; i<routeResult.nodePositions.length; i++){
            //var strCoordTemp = (Math.round(routeResult.nodePositions[i].x*1000000))/1000000 + ',' + (Math.round(routeResult.nodePositions[i].y*1000000))/1000000;
            
            //GetRouteMap.aspx test
            //alert(routeResult.nodePositions[i].y.toFixed(6) + ',' + routeResult.nodePositions[i].x.toFixed(6) );
            
            var strCoordTemp = routeResult.nodePositions[i].x.toFixed(6) + ',' + routeResult.nodePositions[i].y.toFixed(6);
            arrPosition.push(strCoordTemp);
        }
      }
      
//routeResult.pathGuides[0].pathGuideItems.length
      if(routeResult.pathGuides){
        var strR = "";
//      var myDir, myCost, myEdge, myEdgename, myDist, myDistAll, myTime, myPedID, myToll, myTollAll, myPermit, myVehicle;
        var myDir, myCost, myEdge, myPreEdgeName, myEdgeName, myDist, myDistAll, myTime, myPedID, myToll, myTollAll, myPermit, myVehicle, myTurn, myTurnBe, myTurnE, myProhibitions;
        var isShowTip = 0;
        var myNode, myNodeName, myLon, myLat;
        var myFlag, myNodeAll, myNodeAllArr, myEdgeAll, myEdgeAllArr;
        
        //winsen 2010.2.3
        var stnArray = new Array(), sttaArray = new Array();
        ////////////////
        
            var id;
            myEdge = "";
        myDist = 0;
        myDistAll = 0;
        myTime = 0;
        myCost = 0;
        myPedID = 0;//pedestrian zone
        myToll = 0;
        myTollAll = 0;
        myPermit = 0;
        myVehicle = 0;
        myProhibitions = '0';
        myTurnBe = 0;
        myTurnE = 0;
        myTurn = 0;
        id = 0;
        strPathInfo = '';
        smEdges = new Array();
        clearLine();
        var isNewNode = true;
        var isSameEdge = true;
        var isFTEdge = false;
        var edgeRatio = 1.0; 
        var arrLength = -1;
        var n_msg = '';
        var debug_message_20130207= '';
        var prohibition_route = false;

        for (var i=0; i<routeResult.pathGuides[0].pathGuideItems.length; i++){
            if (routeResult.pathGuides[0].pathGuideItems[i].isEdge == false && prohibition_route == false){ 
			//Node
                var n_End_Point = false;
                if(i+1 < (routeResult.pathGuides[0].pathGuideItems.length) ){
                    var n_route_weight = parseFloat(routeResult.pathGuides[0].pathGuideItems[i+1].weight);
                    if((i+1) == 1 || (i+1) == (routeResult.pathGuides[0].pathGuideItems.length-2) ){
                        myEdgeAll = routeResult.pathGuides[0].pathGuideItems[i+1].name;
                        //alert(i + ':' + myEdgeAll);
                        myEdgeAllArr = myEdgeAll.split("|");
                        var fullDistance;
                        var partDistance;
                        fullDistance = parseFloat(myEdgeAllArr[1]);
                        partDistance = parseFloat(routeResult.pathGuides[0].pathGuideItems[i+1].length);                 
                        var n_original_rate = 0;
                        n_original_rate = (fullDistance / partDistance) * n_route_weight;
                    }
                    else{
                        n_original_rate = n_route_weight;
                    }
                    
                    if(n_original_rate > 100000){
                        n_End_Point = true;
                    }
                }
                

                arrLength  = arrLength + 1;
                gAllNode[arrLength] = routeResult.pathGuides[0].pathGuideItems[i].id;
                if(i==0){
                    //起点
                    myNodeName = dispStartPoint[langMod]; 
                    myDir = routeResult.pathGuides[0].pathGuideItems[i].turnType;
                    //alert("Direction " + myDir);
                    myLon = routeResult.pathGuides[0].pathGuideItems[i].bounds.rightTop.x.toFixed(6);
                    myLat = routeResult.pathGuides[0].pathGuideItems[i].bounds.rightTop.y.toFixed(6);
                    //myNode = myLon + ',' + myLat + ',' + myNodeName + ',' + myDir;
                    myNode = myLon + ',' + myLat + ',' + myNodeName + ',' + myDir;
                    realNode.push(myNode);
                    isNewNode = true;
                }else if (i == (routeResult.pathGuides[0].pathGuideItems.length-1) || n_End_Point){
                    //终点
                    myNodeName = "End"; 
                    myDir = routeResult.pathGuides[0].pathGuideItems[i].turnType;
                    //alert("Direction " + myDir);
                    myLon = routeResult.pathGuides[0].pathGuideItems[i].bounds.rightTop.x.toFixed(6);
                    myLat = routeResult.pathGuides[0].pathGuideItems[i].bounds.rightTop.y.toFixed(6);
                    n_end_node_lat = myLat;
                    n_end_node_lon =  myLon;
                    myNode = myLon + ',' + myLat + ',' + myNodeName + ',' + myDir;
                    realNode.push(myNode);
                    //alert('End Point Found');
                }else{
                    myNodeAll = routeResult.pathGuides[0].pathGuideItems[i].name;
                    myNodeAllArr = myNodeAll.split("|");
                    myNodeName = myNodeAllArr[0].replace(/,/g,"，");
                    myDir = routeResult.pathGuides[0].pathGuideItems[i].turnType;
                    //alert("Direction " + myDir);
                    myLon = routeResult.pathGuides[0].pathGuideItems[i].bounds.rightTop.x.toFixed(6);
                    myLat = routeResult.pathGuides[0].pathGuideItems[i].bounds.rightTop.y.toFixed(6);
                    myNode =  myLon + ',' + myLat + ',' + myNodeName + ',' + myDir;
                }
            }else if (routeResult.pathGuides[0].pathGuideItems[i].isEdge == true && prohibition_route == false){ 
			//Edge
                var n_route_weight = parseFloat(routeResult.pathGuides[0].pathGuideItems[i].weight);
                var n_original_rate = 0;
                gAllEdge[arrLength] = routeResult.pathGuides[0].pathGuideItems[i].id;
                gAllEdgeLength[arrLength] = routeResult.pathGuides[0].pathGuideItems[i].length;
                myEdgeAll = routeResult.pathGuides[0].pathGuideItems[i].name;
                //alert(i + ':' + myEdgeAll);
                myEdgeAllArr = myEdgeAll.split("|");
                
                /*
                myTurnE = myEdgeAllArr[8];
                //alert(myTurnBe + ' = ' + myTurnE);
                myTurn = isTurnEqual(myTurnBe,myTurnE);
                //alert(myTurn);
                myTurnBe = myEdgeAllArr[7];
                */
                debug_content += myEdgeAllArr[0] + ' - permit : ' + myEdgeAllArr[5] + '<br/>';
                
                //alert(myEdgeAllArr[0] + ' - permit : ' + myEdgeAllArr[5]);
                
                if (i==1 || i == (routeResult.pathGuides[0].pathGuideItems.length-2)){
                    var fullDistance;
                    var partDistance;
                    isFTEdge = true;    
                    
                    //0@NGA CHEUNG ROAD|999999.000|13.39055|0|0|0|111009#15890#15888# 0|0|0|0|+|+
                    fullDistance = parseFloat(myEdgeAllArr[1]);
                    partDistance = parseFloat(routeResult.pathGuides[0].pathGuideItems[i].length);

                    if (partDistance < fullDistance){
                        edgeRatio = partDistance/fullDistance;
                    }else{
                        edgeRatio = 1;
                    }
                    
                    n_original_rate = (fullDistance / partDistance) * n_route_weight;
                    debug_message_20130207+='Type A \n';
                }else{
                    isFTEdge = false;   
                    edgeRatio = 1.0;
                    n_original_rate = n_route_weight;
                    debug_message_20130207+='Type B \n';
                }
                //alert(routeResult.pathGuides[0].pathGuideItems[i].id + ',' + n_original_rate);
                debug_message_20130207 += routeResult.pathGuides[0].pathGuideItems[i].id + ' - [' + myEdgeAll +']' + '\n' + n_original_rate + '\n' + parseFloat(myEdgeAllArr[1]) + ',' +fullDistance + '\n' + partDistance + '\n' + n_route_weight + '\n';
                if(n_original_rate > 100000 || parseFloat(myEdgeAllArr[1]) > 900000){
                //alert(routeResult.pathGuides[0].pathGuideItems[i].id + ',' + n_original_rate);
                    prohibition_route = true;
                }else{
                    var n_next_edge_prohibition = false;
                    // check if next edge is prohibition
                    if( (i+2) < (routeResult.pathGuides[0].pathGuideItems.length) ){
                    
                        var n_next_edge_items = routeResult.pathGuides[0].pathGuideItems[i+2].name;
                        var n_next_edge_array = n_next_edge_items.split("|");
                
                        var n_next_full_dist = parseFloat(n_next_edge_array[1]);
                        var n_next_part_dist = parseFloat(routeResult.pathGuides[0].pathGuideItems[i+2].length);
                        
                        var n_next_weight = parseFloat(routeResult.pathGuides[0].pathGuideItems[i+2].weight);
                        
                        if(n_next_part_dist > 0){
                            if( ((n_next_full_dist / n_next_part_dist) * n_next_weight) > 100000 ) { n_next_edge_prohibition=true; }
                        }else{
                            if(n_next_weight > 100000 ){ n_next_edge_prohibition=true; }
                        }
                    }

                    if (routeResult.pathGuides[0].pathGuideItems[i].weight && routeResult.pathGuides[0].pathGuideItems[i].weight!=""){
    //                  myCost = myCost + edgeRatio * parseFloat(routeResult.pathGuides[0].pathGuideItems[i].weight);
                        myCost = myCost + parseFloat(routeResult.pathGuides[0].pathGuideItems[i].weight);
                    }//累计时间1

                    if (myEdgeAllArr[1] && myEdgeAllArr[1]!=""){
                        myDistAll = myDistAll + edgeRatio * parseFloat(myEdgeAllArr[1]);
                    }//累计距离

                    if (myEdgeAllArr[2] && myEdgeAllArr[2]!=""){
                    n_msg += '\n' + myTime;
                        myTime = myTime + edgeRatio * parseFloat(myEdgeAllArr[2]);
                        var routeEdgeRatio = edgeRatio;
                        var routeTime = parseFloat(myEdgeAllArr[2]);
                        var totalRouteTime = myTime;
                        debug_message_20130207 += 'Edge Ration: ' + routeEdgeRatio + '\n' + 'Route Time: ' + routeTime + '\n' + 'Total Route Time: ' + totalRouteTime + '\n';
                    }//累计时间2

                    if (myEdgeAllArr[4] && myEdgeAllArr[4]!="" && myEdgeAllArr[4]!="0"){
                        myTollAll = myTollAll + parseFloat(myEdgeAllArr[4]);
                    }//累过路费
                    
                    //winsen 2010.2.3
                    if(myEdgeAllArr[10] && myEdgeAllArr[10]!="" && myEdgeAllArr[10] != "+" && myEdgeAllArr[10] != "0")
                    {
                        stnArray.push(myEdgeAllArr[10]);
                    }
                    
                    if(myEdgeAllArr[11] && myEdgeAllArr[11]!="" && myEdgeAllArr[11] != "+" && myEdgeAllArr[11] != "0")
                    {
                        sttaArray.push(myEdgeAllArr[11]);
                    }
                    ////////////
                    if (isNewNode == true){
                        myEdgeName = myEdgeAllArr[0];
                        myDist = edgeRatio * parseFloat(myEdgeAllArr[1]);
                        myPedID = myEdgeAllArr[3];
                        if (myPedID>0){
                            isShowTip = 1;  
                        }
    //                  myToll = myEdgeAllArr[4];
                        myToll = parseFloat(myEdgeAllArr[4]);
                        if (myPermit==0)
                        {
                            myPermit = myEdgeAllArr[5];
                        }
                        var iVehicle = myEdgeAllArr[6];
                        var myFNode =gAllNode[arrLength];
                        var myTNode = routeResult.pathGuides[0].pathGuideItems[i+1].id;
                        myVehicle = getVehicle(iVehicle, myFNode);
                        
                        var iProhibitions = myEdgeAllArr[9];
                        //alert(iProhibitions+','+myFNode+','+myTNode);
                        //myProhibitions = getVehicle(iProhibitions, myFNode);
                        myProhibitions = getVehicleAtFirstEdge(iProhibitions, myFNode, myTNode);
                        
                        myTurnE = myEdgeAllArr[8];
                        //alert(myTurnBe + ' = ' + myTurnE);
                        myTurn = isTurnEqual(myTurnBe,myTurnE);
                        //alert(myTurn);
                        myTurnBe = myEdgeAllArr[7];
                        //alert(myProhibitions);
    //                  if (myVehicle>0){
    //                      isShowTip = 1;  
    //                  }
                        isNewNode = false;
                    }else{
                        var iVehicle = myEdgeAllArr[6];
                        var myFNode =gAllNode[arrLength];
                        var myVehicle_new = getVehicle(iVehicle, myFNode);
                        var iProhibitions = myEdgeAllArr[9];
                        var myPermit_new = myEdgeAllArr[5];
                        //alert(iProhibitions);
                        myProhibitions_new = getVehicle(iProhibitions, myFNode);
                        myTurnE = myEdgeAllArr[8];
                        //alert(myTurnBe + ' = ' + myTurnE);
                        myTurn_new = isTurnEqual(myTurnBe,myTurnE);
                        //alert(myTurn);
                        myTurnBe = myEdgeAllArr[7];
                        //alert((myEdgeName + '#' + myPedID + '#' + myVehicle + '#' + myProhibitions) + '\n' + (myEdgeAllArr[0] + '#' +  myEdgeAllArr[3] + '#' + myVehicle_new + '#' + myProhibitions_new));
                        if ((myPermit!=0 || myPermit_new==0) && (myTurn_new==myTurn) && ((myEdgeName + '#' + myPedID + '#' + myVehicle + '#' + myProhibitions) == (myEdgeAllArr[0] + '#' +  myEdgeAllArr[3] + '#' + myVehicle_new + '#' + myProhibitions_new))){
    //                  if ((myEdgeName + '#' + myPedID + '#' + myToll + '#' + myVehicle) == (myEdgeAllArr[0] + '#' +  myEdgeAllArr[3] + '#' +  myEdgeAllArr[4] + '#' + myEdgeAllArr[6])){
                        //if ((myEdgeName + '#' + myPedID + '#' + myVehicle) == (myEdgeAllArr[0] + '#' +  myEdgeAllArr[3] + '#' + myEdgeAllArr[6])){
                            myDist = myDist + edgeRatio * parseFloat(myEdgeAllArr[1]);
                            myToll = myToll + parseFloat(myEdgeAllArr[4]);
                            isSameEdge = true;
                            debug_content += 'case 1 <br/>';
                        }else if ((myPermit!=0 || myPermit_new==0) && (myVehicle=='0') && (myProhibitions=='0') && (myVehicle_new=='0') && (myProhibitions_new=='0') && (myTurn_new==0) && (myTurn==0) && (myEdgeAllArr[0]=="" || myEdgeAllArr[0]=="-99" || myEdgeAllArr[0] == "Slip Road" || myEdgeAllArr[0] == "支路" || myEdgeAllArr[0].match('@$') || myEdgeAllArr[0].match('@-99$') || myEdgeAllArr[0].match('@Slip Road$') || myEdgeAllArr[0].match('@支路$'))){
                            myDist = myDist + edgeRatio * parseFloat(myEdgeAllArr[1]);
                            isSameEdge = true;
                            debug_content += 'case 2 <br/>';
                        }else{
                            myEdge = '' + myEdgeName.replace(/&/g,"&amp;").replace(/,/g,"，") + ',' + myDist + ',' + myPedID + ',' + myToll + ',' + myPermit + ',' + myVehicle + ',' + myTurn + ',' + myProhibitions;
                            realNode.push(myNode);
                            realEdge.push(myEdge);
                            id = id + 1;
                            myEdgeName = myEdgeAllArr[0];
                            myDist = edgeRatio * parseFloat(myEdgeAllArr[1]);
                            myPedID = myEdgeAllArr[3];
                            if (myPedID>0){
                                isShowTip = 1;  
                            }
    //                      myToll = myEdgeAllArr[4];
                            myToll = parseFloat(myEdgeAllArr[4]);
                            if (myPermit == 0)
                            {
                                myPermit = myEdgeAllArr[5];
                            }
                            myVehicle = myVehicle_new;
                            myProhibitions = myProhibitions_new;
                            myTurn = myTurn_new;
                            debug_content += 'case 3 <br/>';
                        }
                    }
                    
                    if(i == (routeResult.pathGuides[0].pathGuideItems.length-2) || n_next_edge_prohibition == true){
                        myEdge = '' + myEdgeName.replace(/&/g,"&amp;").replace(/,/g,"，") + ',' + myDist + ',' + myPedID + ',' + myToll + ',' + myPermit + ',' + myVehicle + ',' + myTurn + ',' + myProhibitions;
                        realEdge.push(myEdge);
                        id = id + 1;
                    }
                
                }
            }
            
        }
        
        OpenWindowForText(debug_message_20130207,'routedebug');
        
        var tempA = arrPosition.join(";");
        var tempB = realNode.join(";");
        var tempC = realEdge.join(";");
            
//      var intPosition=0;
//3,---build route desc----
        var myPrePedID;
        var myPreToll;
        var myPrePermit;
        var myPreVehicle;
        var myPreTurnB;
        var myPreTurnE;
        var myPreEdgeName_veh;
        var curPos; //save the position
        curPos = 0;

        for (var i = 0; i < id ; i++){
            myNode = realNode[i];
            var arr_myNode = myNode.split(",");
                myLon = arr_myNode[0];
                myLat = arr_myNode[1];
//              myNodeName = arr_myNode[2];
                myDir = arr_myNode[3];
                var myLonLat = arr_myNode[0] + ',' + arr_myNode[1];
                
                var myNodeNext = realNode[i+1];
                var arr_myNodeNext = myNodeNext.split(",");
                myLonLatNext = arr_myNodeNext[0] + ',' + arr_myNodeNext[1];
                
                myEdge = realEdge[i];  //myEdge = myEdgeName + ',' + myDist + ',' + myPedID + ',' + myToll + ',' + myPermit + ',' + myVehicle;
                var arr_myEdge = myEdge.split(",");
                
                if (i==0){
                    myPreEdgeName = dispStartPoint[langMod];
                    myPrePedID = 0;
                    myPreToll = 0;
                    myPrePermit = 0;
                    myPreVehicle = '0';
                    myPreProhibitions = '0';
                    myPreTurnB = 0;
                    myPreTurnE = 0;
                }else{
                    myPreEdgeName = myEdgeName;
                    myPreEdgeName_veh = myEdgeName;
                    myPrePedID = myPedID;
                    myPreToll = myToll;
                    myPrePermit = myPermit;
                    myPreVehicle = myVehicle;
                    myPreProhibitions = myProhibitions;
                    myPreTurnB = 0;//myTurnB;
                    myPreTurnE = myTurnE;
                    
                }

                myEdgeName = arr_myEdge[0];
                myDist = arr_myEdge[1];
                myPedID = arr_myEdge[2];
                if (myPedID>0){
                isShowTip = 1;  
            }
//              myToll = arr_myEdge[3];
                myToll = parseFloat(arr_myEdge[3]);
                myPermit = arr_myEdge[4];
                myVehicle = arr_myEdge[5];
                myTurn = arr_myEdge[6];
                myProhibitions =  arr_myEdge[7];
//              if (myVehicle>0){
//              isShowTip = 1;  
//          }
//alert(i + ' : ' + myTurn);
            var mPoints = new Array()
            var isBegin = false;
            //for (j=0; j < arrPosition.length; j++)
            for (j=curPos; j < arrPosition.length; j++){
                var tempPos = arrPosition[j];
                var arrPos = tempPos.split(",");
                if (parseFloat(arr_myNode[0]).toFixed(5)==parseFloat(arrPos[0]).toFixed(5) && parseFloat(arr_myNode[1]).toFixed(5)==parseFloat(arrPos[1]).toFixed(5)){
                //if (myLonLat == arrPosition[j]){
                    isBegin=true;   
                }
                if(isBegin==true){
                    var mlonLat = new OpenLayers.LonLat(arrPos[0],arrPos[1]);   
                    mlonLat.transform(map.displayProjection,map.getProjectionObject()); 
                        var mPoint= new OpenLayers.Geometry.Point(mlonLat.lon, mlonLat.lat);
                        mPoints.push(mPoint);
                }
                if (parseFloat(arr_myNodeNext[0]).toFixed(5)==parseFloat(arrPos[0]).toFixed(5) && parseFloat(arr_myNodeNext[1]).toFixed(5)==parseFloat(arrPos[1]).toFixed(5)){
                //if (myLonLatNext == arrPosition[j]){
                    isBegin = false;
                    curPos = j;
                        break;  
                    }
            }
            smEdges.push(mPoints);
//          strR = strR + createPathItem(i, myDir, myEdgeName, myDist, myNodeName, myLon, myLat, myPedID, myPermit, myToll, myVehicle);
                var imageName;
                var turnName
                if (lang=='SC'){
                    myPreEdgeName = t2s(myPreEdgeName);
                    myEdgeName = t2s(myEdgeName);
                }
                if (myDir == "0"){
                    imageName = "arrow_up.gif";
                    turnName = dispTurnTo[langMod]; //" turn To ";  
                } else if (myDir == "1"){
                    imageName = "arrow_left.gif";
                    turnName = dispTurnLeftTo[langMod]; //" turn left to "; 
                } else if (myDir == "2"){
                    imageName = "arrow_right.gif";
                    turnName = dispTurnRightTo[langMod]; //" turn right to ";   
                } else if (myDir == "3"){
                    imageName = "arrow_up.gif";
                    turnName = dispKeepGoingTo[langMod]; //" keep going to ";   
                } else if (myDir == "4"){
                    imageName = "arrow_round.gif";
                    turnName = dispTurnRoundTo[langMod];  //" turn round to";   
                }
                if (myEdgeName.indexOf('Exit')>-1 || myEdgeName.indexOf('出口')>-1) {
                    turnName = dispchoose[langMod];
                    imageName = "arrow_no.gif";
                }
                
                //alert( i + '\n' + myEdgeName + '\n' + myPreEdgeName);
                if (myEdgeName=="" || myEdgeName=="-99" || myEdgeName=="Slip Road" || myEdgeName=="支路"  || myEdgeName.match('@$') || myEdgeName.match('@-99$') || myEdgeName.match('@Slip Road$') || myEdgeName.match('@支路$')){
                    if(myEdgeName.indexOf('@')>-1){
                        myEdgeName= myEdgeName.substring(0,myEdgeName.indexOf('@')+1) + dispNoNameRoad[langMod]; //"No Name Road";  
                    }
                    else{
                        myEdgeName=dispNoNameRoad[langMod]; //"No Name Road";   
                    }
                }
                if (myPreEdgeName=="" || myPreEdgeName=="-99" || myPreEdgeName=="Slip Road" || myPreEdgeName=="支路"  || myPreEdgeName.match('@$') || myPreEdgeName.match('@-99$') || myPreEdgeName.match('@Slip Road$') || myPreEdgeName.match('@支路$')){
                    if(myPreEdgeName.indexOf('@')>-1){
                        myPreEdgeName= myPreEdgeName.substring(0,myPreEdgeName.indexOf('@')+1) + dispNoNameRoad[langMod]; //"No Name Road"; 
                    }
                    else{
                        myPreEdgeName=dispNoNameRoad[langMod]; //"No Name Road";    
                    }
                }
                myPreEdgeName = myPreEdgeName.replace(/&apos;/,"'");
                myEdgeName = myEdgeName.replace(/&apos;/,"'");
                //handle route num icon, 2011enhancement_item2. Route No. of Strategic Roads
                myPreEdgeName = addRouteIcon(myPreEdgeName);
                myEdgeName = addRouteIcon(myEdgeName);
                
                //alert(myDist);
                myDist = Math.round(myDist) + dispMeas[langMod];
                //alert(myDist);
                
                if (myPreEdgeName == myEdgeName && (myPreVehicle>0 || myPrePedID>0 || myPreToll>0)){
                    imageName = "arrow_up.gif";
                    if (langMod == 0){
                        var str='<table width="100%" border="0" cellpadding="0" cellspacing="0" id="hotelname"><tr>';
                        str = str + '<td width="2" ><img src="images/spacer.gif" alt="" width="2" height="1" border="0" /></td>';
                        str = str + '<td width="15" valign="top" class="normalText"><a href="#">' + (i+1) + '.</a></td>';
                      str = str + '<td width="5" class="normalText"><img src="images/spacer.gif" alt="" width="5" height="1" border="0" /></td>';
                      str = str + '<td width="13" valign="top" ><img src="images/' + imageName + '" alt="" width="13" height="13" border="0" /></td>';
                      str = str + '<td width="5" class="normalText"><img src="images/spacer.gif" alt="" width="5" height="1" border="0" /></td>';
                      str = str + '<td valign="top" class="normalText routeTDheight"><a class="routeText" href="#" onclick="clearSelectWin2('+i+');positionPoint(' + (i) + ',' + myLon + ',' + myLat + ')">Keep going on ' + myEdgeName + '</a>';
                    }else{
                      var str='<table width="100%" border="0" cellpadding="0" cellspacing="0" id="hotelname"><tr>';
                        str = str + '<td width="2" ><img src="images/spacer.gif" alt="" width="2" height="1" border="0" /></td>';
                        str = str + '<td width="15" valign="top" class="normalText"><a href="#">' + (i+1) + '.</a></td>';
                        str = str + '<td width="5" class="normalText"><img src="images/spacer.gif" alt="" width="5" height="1" border="0" /></td>';
                        str = str + '<td width="13" valign="top" ><img src="images/' + imageName + '" alt="" width="13" height="13" border="0" /></td>';
                        str = str + '<td width="5" class="normalText"><img src="images/spacer.gif" alt="" width="5" height="1" border="0" /></td>';
                        str = str + '<td valign="top" class="normalText routeTDheight"><a class="routeText" href="#" onclick="clearSelectWin2('+i+');positionPoint(' + (i) + ',' + myLon + ',' + myLat + ')">沿' + myEdgeName + '走</a>'; 
                    }
                }else{
                  /*if (myPreVehicle>0){
                        myPreEdgeName = myPreEdgeName + '<b>(' + dispVehicle[langMod] + ')</b>';
                    }
                    if (myPreToll>0){
                    myPreEdgeName = myPreEdgeName + ' <b>('+disToll[langMod]+':$' + myPreToll + ')</b>';    
                    }
                    */
                    var str='<table width="100%" border="0" cellpadding="0" cellspacing="0" id="hotelname"><tr>';
                    str = str + '<td width="2" ><img src="images/spacer.gif" alt="" width="2" height="1" border="0" /></td>';
                    str = str + '<td width="15" valign="top" class="normalText"><a href="#">' + (i+1) + '.</a></td>';
                    str = str + '<td width="5" class="normalText"><img src="images/spacer.gif" alt="" width="5" height="1" border="0" /></td>';
                    str = str + '<td width="13" valign="top" ><img src="images/' + imageName + '" alt="" width="13" height="13" border="0" /></td>';
                    str = str + '<td width="5" class="normalText"><img src="images/spacer.gif" alt="" width="5" height="1" border="0" /></td>';
                    str = str + '<td valign="top" class="normalText routeTDheight"><a class="routeText" href="#" onclick="clearSelectWin2('+i+');positionPoint(' + (i) + ',' + myLon + ',' + myLat + ')">' + myPreEdgeName + turnName + myEdgeName + '</a>';
                }
              if (myPedID>0){
                str = str + ' <a class="routeText" valign="bottom" href="#" onclick="openPedZone(' + myPedID + ','+i+')"><b>(' + dispPartTimePedestrianStreet[langMod] + ')</b></a>';
                lineFeature_green = new OpenLayers.Feature.Vector(new OpenLayers.Geometry.LineString(smEdges[i]));
                vectorLayer_green.addFeatures([lineFeature_green]);
                isShowTip = 1;  
                //alert(vectorLayer_green.features.length);
              }
              if (myPermit>0){
                str = str + ' <b>(' + dispPermit[langMod] + ')</b>';
                lineFeature_green = new OpenLayers.Feature.Vector(new OpenLayers.Geometry.LineString(smEdges[i]));
                vectorLayer_green.addFeatures([lineFeature_green]);
                isShowTip = 1;  
              }
              if (myTurn>0){
                str = str + ' <a class="routeText" valign="bottom" href="#" onclick="openTurn(' + myTurn + ','+i+')"><b>(' + dispTurn[langMod] + ')</b></a>';
                isShowTip = 1;  
              }
              if (myVehicle!='0'){
                //str = str + ' <b>(' + dispVehicle[langMod] + ')</b>';
                var tempPara="";
                tempPara =  "a" + myVehicle;
                str = str + ' <a class="routeText" valign="bottom" href="#" onclick="openVehicle(\'' + tempPara + '\','+i+');"><b>(' + dispVehicle[langMod] + ')</b></a>';
                isShowTip = 1;  
              }
              if (myProhibitions!='0'){
                var tempPara="";
                tempPara =  "a" + myProhibitions;
                str = str + ' <a class="routeText" valign="bottom" href="#" onclick="openProhibitions(\'' + tempPara + '\','+i+');"><b>(' + dispProhibitions[langMod] + ')</b></a>';
                isShowTip = 1;  
              }
              
              if (myToll>0){
                str = str + ' <b>('+disToll[langMod]+':$' + myToll + ')</b>';   
              }
              
              str = str + '<br/><img src="images/spacer.gif" alt="" width="1" height="1" border="0" /></td><td width="50" valign="top" class="normalText"><div align="right">' + myDist + '</div></td></tr></table>';
              
                str = str + '<table width="100%" border="0" cellpadding="0" cellspacing="0" id="tableblankline"><tr>';
                str = str + '<td height="3" colspan="5" ><img src="images/spacer.gif" alt="" width="1" height="3" border="0" /></td>';
                str = str + '</tr></table>';
                
                str = str + '<table width="100%" border="0" cellpadding="0" cellspacing="0" id="tableline"><tr>';
                str = str + '<td width="30" height="3" colspan="3" background="images/table_line_bg.gif"><img src="images/spacer.gif" alt="" width="1" height="3" border="0" /></td></tr><tr>';
                str = str + '<td height="3" colspan="3" ><img src="images/spacer.gif" alt="" width="1" height="3" border="0" /></td>';
                str = str + '</tr></table>';
                        
            strR = strR + str; //createPathItem(i, myDir, myPreEdgeName, myEdgeName, myDist, myNodeName, myLon, myLat, myPedID, myPermit, myToll, myVehicle);

//          strPathInfo = strPathInfo + "<item id='" + i + "' dir='" + myDir + "' edge='" + myEdgeName.replace(/&/g,"&amp;").replace(/'/g,"&apos;") + "' distance='" + myDist + "' node='" + myNodeName.replace(/&/g,"&amp;").replace(/'/g,"&apos;") + "' pedID='" + myPedID + "'></item>";
            if (lang=='SC'){
                    myPreEdgeName = t2s(myPreEdgeName);
                    myEdgeName = t2s(myEdgeName);
                    myNodeName = t2s(myNodeName);
                }   
            strPathInfo = strPathInfo + "<item id='" + i + "' dir='" + myDir + "' edge='" + myEdgeName.replace(/&/g,"&amp;").replace(/'/g,"&apos;").replace(/</g,"&lt;").replace(/>/g,"&gt;")+ "' distance='" + myDist + "' node='" + myNodeName.replace(/&/g,"&amp;").replace(/'/g,"&apos;") + "' pedID='" + myPedID + "' Permit='" + myPermit + "' Toll='" + myToll + "' Vehicle='" + myVehicle + "' Turn='" + myTurn + "' Prohibitions='" + myProhibitions + "'></item>";
        }
        
            //for harbour crossing and permit
            if (myPermit>0){
            isShowTip = 1;  
            }
            changeHarbourItem(nodeHarbour,isShowTip);
            
        //distance
        var divD = document.getElementById('pathDistance');
            strDistance = (Math.round(myDistAll/100))/10;
            divD.innerHTML = strDistance;
            //travel time
            var divT = document.getElementById('pathTime');
//          divT.innerHTML = Math.floor((myTime)/60) + dispMins[langMod]; //"Mins";             
//          if (userContext=="STR"){
                //divT.innerHTML = Math.floor((myCost)/60);
//              divT.innerHTML = Math.floor((myTime)/60);
//          }else{
n_msg += '\n' + myTime;
                OpenWindowForText(n_msg,'nelson_test');
                //edit by lawrencekai 20130513
                //divT.innerHTML = Math.floor((myTime)/60);
                divT.innerHTML = Math.round(((myTime)/60) * 10) / 10 ;
                overallTime = divT.innerHTML;
                debug_message_20130207 += 'Overall Time: ' + overallTime + '\n';
//          }
        OpenWindowForText(debug_message_20130207,'routedebug');
            //Toll fee
        var divT = document.getElementById('pathToll');
//          divT.innerHTML = "$" + myTollAll;
            divT.innerHTML = myTollAll;
            //detail info
        var divR = document.getElementById('pathResult');
            divR.innerHTML = strR;
        
            //for harbour crossing [get distance and time]
            getSP2(nodeHarbour, userContext);
      }
      
      if(routeResult.nodePositions){
        var pointList = new Array();
        //var style_blue;
        //clear Line
        
        strCoords = '';
        strCoordTemp = (Math.round(fromLon*1000000))/1000000 + ',' + (Math.round(fromLat*1000000))/1000000; 
        //arrPosition.push(strCoordTemp);
        strCoords = strCoordTemp;
        var lonLat = new OpenLayers.LonLat(fromLon,fromLat) ;
            lonLat.transform(map.displayProjection,map.getProjectionObject());  
            var newPoint= new OpenLayers.Geometry.Point(lonLat.lon, lonLat.lat);
            var space1 = 5;
            var space2 = 10;
            var space3 = 30;
            var space4 = 70;
        
        for (var i=0; i<routeResult.nodePositions.length; i++){
        
            
            
            //var strCoordTemp = (Math.round(routeResult.nodePositions[i].x*1000000))/1000000 + ',' + (Math.round(routeResult.nodePositions[i].y*1000000))/1000000;
            var strCoordTemp = routeResult.nodePositions[i].x.toFixed(6) + ',' + routeResult.nodePositions[i].y.toFixed(6);
            
            arrPosition.push(strCoordTemp);
            strCoords = strCoords + ';' + strCoordTemp;
            lonLat = new OpenLayers.LonLat(routeResult.nodePositions[i].x,routeResult.nodePositions[i].y) ;
                lonLat.transform(map.displayProjection,map.getProjectionObject());  
                newPoint= new OpenLayers.Geometry.Point(lonLat.lon, lonLat.lat);
                pointList.push(newPoint);
                
                space1++;
                space2++;
                space3++;
                space4++;
                
                if (space1>10){
                    if (getDistanceByLnglat(routeResult.nodePositions[i].x,routeResult.nodePositions[i].y,routeResult.nodePositions[i-1].x,routeResult.nodePositions[i-1].y)>30 && getDistanceByLnglat(routeResult.nodePositions[i-2].x,routeResult.nodePositions[i-2].y,routeResult.nodePositions[i-1].x,routeResult.nodePositions[i-1].y)>30){
                            var myAngle =  getBrng(routeResult.nodePositions[i-2].x,routeResult.nodePositions[i-2].y,routeResult.nodePositions[i].x,routeResult.nodePositions[i].y)
                            MarkerFeature_dir.push(new OpenLayers.Feature.Vector(pointList[i-1], {angle: myAngle}));
                            space1 = 0;
                    }
                }
                if ( space2>21){
                    if (getDistanceByLnglat(routeResult.nodePositions[i].x,routeResult.nodePositions[i].y,routeResult.nodePositions[i-2].x,routeResult.nodePositions[i-2].y)>60 && getDistanceByLnglat(routeResult.nodePositions[i-4].x,routeResult.nodePositions[i-4].y,routeResult.nodePositions[i-2].x,routeResult.nodePositions[i-2].y)>60){
                            var myAngle =  getBrng(routeResult.nodePositions[i-4].x,routeResult.nodePositions[i-4].y,routeResult.nodePositions[i].x,routeResult.nodePositions[i].y)
                            MarkerFeature_dir2.push(new OpenLayers.Feature.Vector(pointList[i-2], {angle: myAngle}));
                            space2 = 0;
                    }
                }
                if (space3>40){
                    if (getDistanceByLnglat(routeResult.nodePositions[i].x,routeResult.nodePositions[i].y,routeResult.nodePositions[i-3].x,routeResult.nodePositions[i-3].y)>120 && getDistanceByLnglat(routeResult.nodePositions[i-6].x,routeResult.nodePositions[i-6].y,routeResult.nodePositions[i-3].x,routeResult.nodePositions[i-3].y)>120){
                            var myAngle =  getBrng(routeResult.nodePositions[i-6].x,routeResult.nodePositions[i-6].y,routeResult.nodePositions[i].x,routeResult.nodePositions[i].y)
                            MarkerFeature_dir3.push(new OpenLayers.Feature.Vector(pointList[i-3], {angle: myAngle}));
                            space3 = 0;
                    }
                }
                if (space4>80){
                    if (getDistanceByLnglat(routeResult.nodePositions[i].x,routeResult.nodePositions[i].y,routeResult.nodePositions[i-4].x,routeResult.nodePositions[i-4].y)>240 && getDistanceByLnglat(routeResult.nodePositions[i-8].x,routeResult.nodePositions[i-8].y,routeResult.nodePositions[i-4].x,routeResult.nodePositions[i-4].y)>240){
                            var myAngle =  getBrng(routeResult.nodePositions[i-8].x,routeResult.nodePositions[i-8].y,routeResult.nodePositions[i].x,routeResult.nodePositions[i].y)
                            MarkerFeature_dir4.push(new OpenLayers.Feature.Vector(pointList[i-4], {angle: myAngle}));
                            space4 = 0;
                    }
                }
                
                //if( n_end_node_lat == routeResult.nodePositions[i].y.toFixed(6) && n_end_node_lon == routeResult.nodePositions[i].x.toFixed(6)){ break;}
            }
            
            strCoordTemp = (Math.round(toLon*1000000))/1000000 + ',' + (Math.round(toLat*1000000))/1000000
            //arrPosition.push(strCoordTemp);
            strCoords = strCoords + ';' + strCoordTemp;  
            //alert (strCoords);
            lonLat = new OpenLayers.LonLat(toLon,toLat) ;
            lonLat.transform(map.displayProjection,map.getProjectionObject());  
            newPoint= new OpenLayers.Geometry.Point(lonLat.lon, lonLat.lat);
      //pointList.push(newPoint);
        lineFeature_blue = new OpenLayers.Feature.Vector(new OpenLayers.Geometry.LineString(pointList));
        vectorLayer_blue.addFeatures([lineFeature_blue]);
            
            //fix to bounds getZoomForExtent
            var smBounds = routeResult.bounds;
            var olBounds = new OpenLayers.Bounds();
            olBounds.extend(new OpenLayers.LonLat(smBounds.leftBottom.x,smBounds.leftBottom.y));
            olBounds.extend(new OpenLayers.LonLat(smBounds.rightTop.x,smBounds.rightTop.y));
            olBounds.transform(map.displayProjection,map.getProjectionObject());
            map.zoomToExtent(olBounds);
    
            isShowPath = true;
            if (map.getZoom() > 17){
                vectorLayer_dir.addFeatures(MarkerFeature_dir);
            }else if (map.getZoom() > 15){
                vectorLayer_dir.addFeatures(MarkerFeature_dir2);
            }else if (map.getZoom() > 12){
                vectorLayer_dir.addFeatures(MarkerFeature_dir3);
            }else {
                vectorLayer_dir.addFeatures(MarkerFeature_dir4);
            }
      }
      
      
      // Henry
      showAvoidToolbar();
      hideLoading();
      time15 = getTimeNow();
      timetestcase();
      edgeIDs = "" + routeResult.edgeIDs;
        
        //winsen 2010.2.3
        stnArray = MergeAndSplit(stnArray, "+");
        stnArray = DeleteRepeatElement(stnArray);
        
        //stn testing
        //alert(stnArray.length);
        
        if(stnArray.length != 0)
        {
            var stnArrayString = "" + stnArray;
            sURL = "http://203.194.149.169/drss/StnDialog.php?lang=" + lang + "&edgeIDs=" + stnArrayString;
            //sURL = "http://drss.td.gov.hk/drss/StnDialog.php?lang=" + lang + "&edgeIDs=" + stnArrayString;
            OpenChildWindow(sURL, '', 400, 400, 600, 400, false);
        }

        
        sttaArray = MergeAndSplit(sttaArray, "+");
        sttaArray = DeleteRepeatElement(sttaArray);
        
        //stta testing
        //alert(sttaArray.length);
        
        if(sttaArray.length != 0)
        {
            var sttaArrayString = "" + sttaArray;
            sURL2 = "http://203.194.149.169/drss/SttaDialog.php?lang=" + lang + "&edgeIDs=" + sttaArrayString;
            //sURL2 = "http://drss.td.gov.hk/drss/SttaDialog.php?lang=" + lang + "&edgeIDs=" + sttaArrayString;
            OpenChildWindow(sURL2, '', 200, 200, 600, 300, false);
        }
        ///////////////
        

    }else{
        if (lang == 'E'){
            str ="<div style='font-size:12px'>&nbsp;&nbsp;&nbsp;&nbsp;Route can not be found from (" + fromLon.toFixed(6) + "," + fromLat.toFixed(6) + ") to (" + toLon.toFixed(6) + "," + toLat.toFixed(6) + ").<br></div>";
        }else if (lang == 'TC'){
            str ="<div style='font-size:12px'>&nbsp;&nbsp;&nbsp;&nbsp;沒有適合路線由 (" + fromLon.toFixed(6) + "," + fromLat.toFixed(6) + ") 至 (" + toLon.toFixed(6) + "," + toLat.toFixed(6) + ").<br></div>";
        }else if (lang == 'SC'){
            str ="<div style='font-size:12px'>&nbsp;&nbsp;&nbsp;&nbsp;没有适合路线由 (" + fromLon.toFixed(6) + "," + fromLat.toFixed(6) + ") 至 (" + toLon.toFixed(6) + "," + toLat.toFixed(6) + ").<br></div>";
        }else{
            str ="<div style='font-size:12px'>&nbsp;&nbsp;&nbsp;&nbsp;Route can not be found from (" + fromLon.toFixed(6) + "," + fromLat.toFixed(6) + ") to (" + toLon.toFixed(6) + "," + toLat.toFixed(6) + ").<br></div>";
        }

        var s3_content=document.getElementById('s3_content');
        s3_content.innerHTML = str; 
    }
    hideLoading();
    TabHtml_1 = e('s3_content').innerHTML;

    OpenWindowForText(debug_content,'debug_content');
    
}

function OpenWindowForText(msg,index){

/*
    index type
    location_point
    uat_textual01
    routedebug
    m1
    m2
    uat_map01
    uat_map_lat_lon_01
    routedebug
    timetest
    nelson_test
    debug_content
*/

    if( index == 'location_point' ){
        var OpenWindow=window.open("", "window" + index, "height=500, width=500,toolbar=no,menubar=no,scrollbars=yes");
        OpenWindow.document.write("<TITLE>Result</TITLE>");
        OpenWindow.document.write("<BODY BGCOLOR=pink>");
        OpenWindow.document.write("<PRE>" + msg + "</PRE>");
        OpenWindow.document.write("</BODY>");
        OpenWindow.document.write("</HTML>");
        OpenWindow.document.close();
    }
    
    return;
}

function addRouteIcon(edgeName){
    //handle route num icon, 2011 enhancement_item2. Route No. of Strategic Roads
    var edgeNameArr;
    if(edgeName.indexOf('@')>-1){
        edgeNameArr = edgeName.split('@');
if(parseInt(edgeNameArr[0]) > 0){
            return edgeNameArr[1] + '<img class="routeImage" src="images/route/' + edgeNameArr[0] + '.png" alt="" border="0" />';
        }
        else{
            return edgeNameArr[1];
        }
    }else{
        return  edgeName;
    }
}

function isTurnEqual(turnB, turnE){
    if (turnB == '0' || turnE == '0'){
        return 0;   
    }   else {
        var arrB = turnB.split(',');
        var arrE = turnE.split(',');
        for (var i=0;i<arrB.length;i++){
            for (var j=0;j<arrE.length;j++){
                if (arrB[i] == arrE[j]){
                    return arrB[i]; 
                }   
            }   
        }   
        return 0;
    }
}
            
function getVehicle(myVehicle, myFNode){
    var iVehicle='0';
    if (myVehicle !='0'){
        var arrMyVehicle =  myVehicle.split('#'); //0:route_id; 1:smfnode; 2:smtnode; 3:offsetall
        var offsetAll = arrMyVehicle[3];
        try{
            if (offsetAll.indexOf('0')>-1){
                iVehicle = arrMyVehicle[0] + 'a0';
            }else{
                if (myFNode == arrMyVehicle[2]){
                    if (offsetAll.indexOf('-2')>-1){
                        iVehicle = arrMyVehicle[0] + 'a-2';
    //          if (myFNode == arrMyVehicle[2]){
    //              if (offsetAll.indexOf('1')>-1){
    //                  iVehicle = arrMyVehicle[0] + 'a1';
                    }else{
                        iVehicle = '0'; 
                    }   
                }else if (myFNode == arrMyVehicle[1]){
                    if (offsetAll.indexOf('1')>-1){
                        iVehicle = arrMyVehicle[0] + 'a1';
    //          }else if (myFNode == arrMyVehicle[1]){
    //              if (offsetAll.indexOf('-2')>-1){
    //                  iVehicle = arrMyVehicle[0] + 'a-2';
                    }else{
                        iVehicle = '0'; 
                    }   
                }
            }
        }
        catch(e){}
    }
    return iVehicle;
}

function getVehicleAtFirstEdge( myVehicle, myFNode, myTNode ){
    if( myFNode > -1 ){ return getVehicle(myVehicle, myFNode); }
    else{
        var iVehicle='0';
        if (myVehicle !='0'){
            var arrMyVehicle =  myVehicle.split('#'); //0:route_id; 1:smfnode; 2:smtnode; 3:offsetall
            var offsetAll = arrMyVehicle[3];
            try{
                if (offsetAll.indexOf('0')>-1){
                    iVehicle = arrMyVehicle[0] + 'a0';
                }else{
                    if (myTNode == arrMyVehicle[1]){
                        if (offsetAll.indexOf('-2')>-1){
                            iVehicle = arrMyVehicle[0] + 'a-2';
        //          if (myTNode == arrMyVehicle[2]){
        //              if (offsetAll.indexOf('1')>-1){
        //                  iVehicle = arrMyVehicle[0] + 'a1';
                        }else{
                            iVehicle = '0'; 
                        }   
                    }else if (myTNode == arrMyVehicle[2]){
                        if (offsetAll.indexOf('1')>-1){
                            iVehicle = arrMyVehicle[0] + 'a1';
        //          }else if (myTNode == arrMyVehicle[1]){
        //              if (offsetAll.indexOf('-2')>-1){
        //                  iVehicle = arrMyVehicle[0] + 'a-2';
                        }else{
                            iVehicle = '0'; 
                        }   
                    }
                }
            }
            catch(e){}
        }
        return iVehicle;
    }
}
        
function onComplete2 (routeResult, userContext){

    //alert("onComplete2");
    
    var strDistance = 0;
    var strTime = "";
    var strToll = 0;
    var divD = document.getElementById('harbLen1');
    if (userContext.substring(0,1) == "1"){
        divD = document.getElementById('harbLen1');
    }else{
        divD = document.getElementById('harbLen2');
    }
    var divT = document.getElementById('harbTime1');
    if (userContext.substring(0,1) == "1"){
        divT = document.getElementById('harbTime1');
    }else{
        divT = document.getElementById('harbTime2');
    }
    var divToll = document.getElementById('harbToll1');
    if (userContext.substring(0,1) == "1"){
        divToll = document.getElementById('harbToll1');
    }else{
        divToll = document.getElementById('harbToll2');
    }
    
    if(!routeResult){
        divD.innerHTML = "Route not available.";
        return;
    }
    if(routeResult.totalLength>0){
//      strDistance = (Math.round(routeResult.totalLength /100))/10 + dispKM[langMod]; //"km";
//      strDistance = (Math.round(routeResult.totalLength /100))/10;
      if(routeResult.pathGuides){
            var myCost, myDist, myTime, myToll;
            myCost = 0;
            myDist = 0;
            myTime = 0;
            myToll = 0;
            strDistance = 0;
          
          var fullDistance;
        var partDistance;
        var edgeRatio = 1.0;
        
        var my_road = '';
        
        for (var i=0; i<routeResult.pathGuides[0].pathGuideItems.length; i++){
            if (routeResult.pathGuides[0].pathGuideItems[i].isEdge == true){
                //Edige
                myEdgeAll = routeResult.pathGuides[0].pathGuideItems[i].name;
                
                my_road += routeResult.pathGuides[0].pathGuideItems[i].id + '|' + myEdgeAll + '\n';
                
                var n_route_weight = parseFloat(routeResult.pathGuides[0].pathGuideItems[i].weight);
                if(n_route_weight > 100000){break;}
                
                myEdgeAllArr = myEdgeAll.split("|");
                if (i==1 || i == (routeResult.pathGuides[0].pathGuideItems.length-2)){
                    fullDistance = parseFloat(myEdgeAllArr[1]);
                        partDistance = parseFloat(routeResult.pathGuides[0].pathGuideItems[i].length);
                        if (partDistance < fullDistance){
                            edgeRatio = partDistance/fullDistance;
                        }else{
                            edgeRatio = 1.0;
                        }
                }else{
                    edgeRatio = 1.0;
                }
                if (routeResult.pathGuides[0].pathGuideItems[i].weight && routeResult.pathGuides[0].pathGuideItems[i].weight!=""){
                    myCost = myCost + parseFloat(routeResult.pathGuides[0].pathGuideItems[i].weight);
                }//累计时间1
                if (myEdgeAllArr[1] && myEdgeAllArr[1]!=""){
                    strDistance = strDistance + edgeRatio * parseFloat(myEdgeAllArr[1]);
                }//累计距离
                if (myEdgeAllArr[2] && myEdgeAllArr[2]!=""){
                    myTime = myTime + edgeRatio * parseFloat(myEdgeAllArr[2]);
                }//累计时间2
                if (myEdgeAllArr[4] && myEdgeAllArr[4]!=""){
                    strToll = strToll + parseFloat(myEdgeAllArr[4]);
                }//累过路费
                
            }
        }
        
        // OpenWindowForText(my_road,userContext.substring(0,1));
        //edit by lawrence kai 20130513
        //  strTime = Math.floor(myTime/60);
        strTime = Math.round((myTime/60) * 10 ) / 10;
/*          if (userContext.substring(1,4)=="STR"){
                strTime = Math.floor(myCost/60);
            }else{
                strTime = Math.floor(myTime/60);
            } */
      }
      strDistance = (Math.round(strDistance/100))/10;
      divD.innerHTML = strDistance;
      divT.innerHTML = strTime;
//    divToll.innerHTML = "$" + strToll;
      divToll.innerHTML = strToll;
    }else{
        divD.innerHTML = "-";
        divT.innerHTML = "-";
        divToll.innerHTML = "-";
    }
    TabHtml_1 = e('s3_content').innerHTML;
}

function onError (responseText, userContext) {
    hideLoading();
    if (lang=='E'){
        alert ('Server Busy. Please try again later.');
    }else if (lang=='TC'){
        alert ('伺服器繁忙中, 請遲些再試.');
    }else if (lang=='SC'){
        alert ('伺服器繁忙中, 请迟些再试.');
    }else{
        alert ('Server Busy. Please try again later.');
    }
/*
    if(responseText){
        alert("get shortest path error. iType is " + userContext);
        var s3_content=document.getElementById('s3_content');
        s3_content.innerHTML = responseText;
    }else{ 
        alert("unknow shortest path error. iType is " + userContext);
    }*/

    
} 

function onError2 (responseText, userContext) {
    if (lang=='E'){
        alert ('Server Busy. Please try again later.');
    }else if (lang=='TC'){
        alert ('伺服器繁忙中, 請遲些再試.');
    }else if (lang=='SC'){
        alert ('伺服器繁忙中, 请迟些再试.');
    }else{
        alert ('Server Busy. Please try again later.');
    }
/*  if(responseText){
        alert("get shortest path error. iType is " + userContext);
        //var s3_content=document.getElementById('s3_content');
        //s3_content.innerHTML = responseText;
    }else{ 
        alert("unknow shortest path error. iType is " + userContext);
    }*/

}

function findRoadName(lon, lat, myAction){
    var mPoint = new SuperMap.IS.MapCoord(lon,lat);
    var mTolerance = 0.002;
    var mQueryParam = new SuperMap.IS.QueryParam();
    //alert (":" + lon + "," + lat);
    clearSkipInclude();
    showLoading();
    mQueryParam.expectCount = 1;
    //mQueryParam.hasGeometry=false;
    mQueryParam.queryAllLayer=false;
    mQueryParam.returnCenterAndBounds=false;
    mQueryParam.returnShape=true;
    mQueryParam.queryLayers= new Array();
    mQueryParam.queryLayers[0] = new SuperMap.IS.QueryLayer();
    mQueryParam.queryLayers[0].layerName = "NetDT@hk";
    mQueryParam.queryLayers[0].returnFields = new Array();
    mQueryParam.queryLayers[0].returnFields[0] = "SmID";
    if (lang=="E"){
        mQueryParam.queryLayers[0].returnFields[1] = "STREET_ENA";
    }else if (lang=="TC"){
        mQueryParam.queryLayers[0].returnFields[1] = "STREET_CNA";  
    }else if (lang=="SC"){
        mQueryParam.queryLayers[0].returnFields[1] = "STREET_CNA";  
    }else{
        mQueryParam.queryLayers[0].returnFields[1] = "STREET_ENA";  
    }
    mQueryParam.queryLayers[0].returnFields[2] = "runinout";
    mQueryParam.queryLayers[0].returnFields[3] = "STREET_ENA";
    mQueryParam.queryLayers[0].returnFields[4] = "route_id";
    
    // route_id = 123436 is CHEONG HONG ROAD at airport
    if (myAction=="doStart" || myAction=="doPoiStart"|| myAction=="doSwapStart"){
        mQueryParam.queryLayers[0].whereClause=" (elevation = 0 or route_id=123436) and (runinout = 0 or runinout = 2)";
    }else if (myAction=="doEnd" || myAction=="doPoiEnd"|| myAction=="doSwapEnd"){
        mQueryParam.queryLayers[0].whereClause=" (elevation = 0 or route_id=123436) and (runinout = 0 or runinout = 1)";
    }else{
        mQueryParam.queryLayers[0].whereClause=" elevation = 0 or route_id=123436";
    }
    
    mQueryParam.returnFields = new Array();
    mQueryParam.returnFields[0] = "SmID";
    if (lang=="E"){
        mQueryParam.returnFields[1] = "STREET_ENA";
    }else if (lang=="TC"){
        mQueryParam.returnFields[1] = "STREET_CNA"; 
    }else if (lang=="SC"){
        mQueryParam.returnFields[1] = "STREET_CNA"; 
    }else{
        mQueryParam.returnFields[1] = "STREET_ENA"; 
    }
    mQueryParam.returnFields[2] = "runinout";
    mQueryParam.returnFields[3] = "STREET_ENA";
    mQueryParam.returnFields[4] = "route_id";
    
    //no highlight no new map request
    mQueryParam.highlight = new SuperMap.IS.Highlight();
    mQueryParam.highlight.highlightResult = false;
  
    var mQueryManager = smMap.GetQueryManager();

    //GetIRNLocation.aspx test
    //alert(lat + ',' + lon);
    //alert('Lat (Original Location): ' + lat.toFixed(6) + ', ' + 'Lng (Original Location): ' + lon.toFixed(6));
    
    mQueryManager.FindNearest(mPoint,mTolerance,mQueryParam,findRoadNameC,findRoadNameE,myAction);

    
}

function findRoadNameC(resultSet,userContext){



if (!resultSet.recordsets)
{
    if (lang=='E'){
        alert ("Unknown Street found, please choose the other location.");
    }else if (lang=="TC"){
        alert ("找尋不到合適路段， 請重新選擇位置。");
    }else if (lang=="SC"){
        alert ("找寻不到合适路段， 请重新选择位置。");
    }else{
        alert ("Unknown Street found, please choose the other location.");
    }
    hideLoading();
}else{
    var intLength = resultSet.recordsets[0].records[0].shape.points.length;
    //var intSpace = 1 + Math.floor( intLength / 40);
    var intSpace = 1;
    var resultP;
    var strFun="";






    //alert(resultSet.recordsets[0].records[0].fieldValues[2]+','+resultSet.recordsets[0].records[0].fieldValues[3]+','+resultSet.recordsets[0].records[0].fieldValues[4]);

    //alert(resultSet.recordsets[0].records[0].fieldValues[1]);































    //show load name
    var strRouteName;
    if (!resultSet || !resultSet.recordsets || !resultSet.recordsets[0].records){
        strRouteNamee = dispNotFound[langMod]; //"Not found!";  





























    }else{

        strRouteName = resultSet.recordsets[0].records[0].fieldValues[1];
        if (strRouteName == '-99' || strRouteName == '' || strRouteName == 'null'){
            strRouteName = dispNoNameRoad[langMod];
        }else if (lang=='SC'){
            strRouteName = t2s(strRouteName);
        }
    }
    //alert(strRouteName);
    if (userContext=="doStart"){
        e("from").value = strRouteName;
    }else if (userContext=="doEnd"){
        e("to").value = strRouteName;
    }
    





















    var debug_string = '';
    

    //calculator new point's coord  
    if (userContext=="doStart" || userContext == "doPoiStart" || userContext == "doSwapStart"){ 
        //strFun="resultP = closestPolyLinePoint(" + fromLon + "," + fromLat;
        strFun='resultP = closestPointFromPolyLine({x:' + fromLon + ',y:' + fromLat + '}';
        debug_string = fromLon + ',' + fromLat + '\n';
        
    } else if(userContext=="doEnd" || userContext=="doPoiEnd" || userContext=="doSwapEnd"){
        //strFun="resultP = closestPolyLinePoint(" + toLon + "," + toLat;
        strFun='resultP = closestPointFromPolyLine({x:' + toLon + ',y:' + toLat + '}';
        debug_string = toLon + ',' + toLat + '\n';
    }
    strFun += ',[';
    
    for (var i = 0; i<intLength; i = i + intSpace){
        var cLon = resultSet.recordsets[0].records[0].shape.points[i].x.toFixed(6);
        var cLat = resultSet.recordsets[0].records[0].shape.points[i].y.toFixed(6);
        //strFun = strFun + "," + cLon + "," + cLat;
        
        if( i > 0){
            strFun += ',{x:' + cLon + ',y:' + cLat + '}';
        }
        else{
            strFun += '{x:' + cLon + ',y:' + cLat + '}';
        }
        debug_string += cLon + ',' + cLat + '\n';
    }
    strFun = strFun + '])';
    //alert (strFun);
    eval(strFun);
    debug_string += '\n' + resultP.x + "," +resultP.y;
    //alert ("x:" + resultP.x + " y:" +resultP.y);
    //alert(debug_string);
    var newLon = resultP.x.toFixed(6);
    var newLat = resultP.y.toFixed(6);
    
    //GetIRNLocation.aspx test
    //alert(newLat + ',' + newLon);
    //alert('Lat (IRN Location): ' + newLat + ', ' + 'Lng (IRN Location): ' + newLon);
    
    var msg_nelson_20130115 = 'Lat (IRN Location):' + '\n';
    msg_nelson_20130115 += newLat + '\n';
    msg_nelson_20130115 += 'Lng (IRN Location):' + '\n';
    msg_nelson_20130115 += newLon + '\n';
    //OpenWindowForText(msg_nelson_20130115,'location_point');
    
    var newLonLat = new OpenLayers.LonLat(newLon, newLat) ;
    newLonLat.transform(map.displayProjection,map.getProjectionObject());
    
    if (userContext=="doStart" || userContext == "doPoiStart" ){    
       fromLon = newLon;
       fromLat = newLat;
    } else if(userContext=="doEnd" || userContext=="doPoiEnd"){
       toLon = newLon;
       toLat = newLat;
    }else if (userContext == "doSwapStart" ){   
       fromLon = newLon;
       fromLat = newLat;
       swapFlag ++;
    } else if(userContext=="doSwapEnd"){
       toLon = newLon;
       toLat = newLat;
       swapFlag ++;
    }else{
        return; //?
    }
    //alert(userContext);
    //auto get the routing result when user locate the "Origin" and "Destination" on the map by using the Map Tool Bar
    if (userContext=="doStart" || userContext=="doEnd" || ((userContext=="doSwapStart" || userContext=="doSwapEnd") && swapFlag>1)){
        if (fromLon > 0 && toLon > 0){
            /*if (e("criteria3").checked){
                init_pathResult();
                getSP0(0, "STS");       //Shortest Travel Time (Static)
                setAction('doPan');
            }else*/ if (e("criteria1").checked){
                init_pathResult();
                getSP0(0, "SD");//Shortest Distance 
                setAction('doPan');
            }else if (e("criteria4").checked){
                init_pathResult();
                getSP0(0, "STR");   //Shortest Travel Time (Real Time)
                setAction('doPan');
            }else if (e("criteria2").checked){
                init_pathResult();
                getSP0(0, "CT");    //Cheapest tunnel/bridge toll
                setAction('doPan');
            }else {
                alert ("Please select Shortest Distance!");
                return; 
            }
        }else{
            hideLoading();
        }
     }else{
        hideLoading();
     }

}
}

function findRoadNameE(responseText,userContext){
    hideLoading();



    if(responseText){
        alert(userContext + ":" + responseText);
    }else{ 
        alert(userContext + ":unknow error!");
    }
}

//
function findNodeID(lon, lat){
    var mPoint = new SuperMap.IS.MapCoord(lon,lat);
    var mTolerance = 0.002;
    var mQueryParam = new SuperMap.IS.QueryParam();
    var strWhereClause = "SmID in (" + gAllNode.join(",") + ")";
    //alert (":" + lon + "," + lat);
    showLoading();
    mQueryParam.expectCount = 1;
    //mQueryParam.hasGeometry=false;
    mQueryParam.queryAllLayer=false;
    mQueryParam.returnCenterAndBounds=false;
    mQueryParam.returnShape=true;
    mQueryParam.queryLayers= new Array();
    mQueryParam.queryLayers[0] = new SuperMap.IS.QueryLayer();
    mQueryParam.queryLayers[0].layerName = "NetDT@hk";
    mQueryParam.queryLayers[0].returnFields = new Array();
    mQueryParam.queryLayers[0].returnFields[0] = "SmID";
    mQueryParam.queryLayers[0].whereClause  = strWhereClause;
    mQueryParam.networkType = 1;
    mQueryParam.returnFields = new Array();
    mQueryParam.returnFields[0] = "SmID";
    
    var mQueryManager = smMap.GetQueryManager();
    mQueryManager.FindNearest (mPoint,mTolerance,mQueryParam,findNodeIDC,findNodeIDE,"findNodeID"); 
}

function findNodeIDC(resultSet,userContext){
    if (!resultSet.recordsets)
    {
        if (lang=='E'){
            alert ("Unknown Street found, please choose the other location.");
        }else if (lang=="TC"){
            alert ("找尋不到合適路口， 請重新選擇位置。");
        }else if (lang=="SC"){
            alert ("找寻不到合适路口， 请重新选择位置。");
        }else{
            alert ("Unknown Street found, please choose the other location.");
        }
        clearSkipInclude();
        hideLoading();
    }else{
        gSkipNode[gSkipInt-1] = resultSet.recordsets[0].records[0].fieldValues[0];
        hideLoading();
        var cLon = resultSet.recordsets[0].records[0].shape.points[0].x.toFixed(6);
        var cLat = resultSet.recordsets[0].records[0].shape.points[0].y.toFixed(6);
        gSkipLon[gSkipInt-1] = cLon;
        gSkipLat[gSkipInt-1] = cLat;
        var lonLat = new OpenLayers.LonLat(cLon, cLat) ;
        lonLat.transform(map.displayProjection,map.getProjectionObject());
        gSkipMarker[gSkipInt-1].move(lonLat);
        if (gSkipInt==2){
            if (gSkipNode[0] == gSkipNode[1]){
                alert(alertAvoid2[langMod]);
                gSkipInt = 1;   
                layerMarkers.removeFeatures(gSkipMarker[1]);    
                return;
            }
            var skipFrom;
            var skipTo;
            var skipTemp
            for(var i=0; i<gAllNode.length; i++){
                if (gAllNode[i] == gSkipNode[0]){
                    skipFrom = i;   
                }
                if (gAllNode[i] == gSkipNode[1]){
                    skipTo = i; 
                }
            }
            if (skipFrom>skipTo){
                skipTemp = skipFrom;
                skipFrom = skipTo;
                skipTo = skipTemp;
            }
            var skipDist = 0.0;
            for (var i=skipFrom; i<skipTo; i++){
                skipDist =  skipDist + gAllEdgeLength[i];
            }
            if (skipDist < 200)
            {
                alert(alertAvoid2[langMod]);
                gSkipInt = 1;   
                layerMarkers.removeFeatures(gSkipMarker[1]);    
            }
        }
    }
}

function findNodeIDE(responseText,userContext){
    clearSkipInclude();
    hideLoading();
    if(responseText){
        alert(userContext + ":" + responseText);
    }else{ 
        alert(userContext + ":unknow error!");
    }
}

function clearLine(){
    if (lineFeature_blue){
        lineFeature_blue.layer.renderer.clear();
        lineFeature_blue.layer.destroyFeatures();
        lineFeature_blue = null;
    }
    if (lineFeature_green){
        lineFeature_green.layer.renderer.clear();
        lineFeature_green.layer.destroyFeatures();
        lineFeature_green = null;
    }
    isShowPath = false;
    if (vectorLayer_dir){
        vectorLayer_dir.destroyFeatures();
        MarkerFeature_dir = [];
        MarkerFeature_dir2 = [];
        MarkerFeature_dir3 = [];
        MarkerFeature_dir4 = [];
    }else{
        MarkerFeature_dir = [];
        MarkerFeature_dir2 = [];
        MarkerFeature_dir3 = [];
        MarkerFeature_dir4 = [];
    }
    if (lineFeature_red){
        lineFeature_red.layer.renderer.clear();
        lineFeature_red.layer.destroyFeatures();
        lineFeature_red = null;
    }
    
}

function obj2str(o){
    var r = [];
    if(typeof o =="string") return "\""+o.replace(/([\'\"\\])/g,"\\$1").replace(/(\n)/g,"\\n").replace(/(\r)/g,"\\r").replace(/(\t)/g,"\\t")+"\"";
    if(typeof o == "object"){
        if(!o || !o.sort){
            for(var i in o)
                r.push('"'+i+'":'+obj2str(o[i]));
            if(!!document.all && !/^\n?function\s*toString\(\)\s*\{\n?\s*\[native code\]\n?\s*\}\n?\s*$/.test(o.toString)){
                r.push("toString:"+o.toString.toString());
            }
            r="{"+r.join()+"}"
        }else{
            for(var i =0;i<o.length;i++)
                r.push(obj2str(o[i]))
            r="["+r.join()+"]"
        }
        return r;
    }
    return o.toString();
}

function init() {



    checkin();

    initRedirect();

    smMap_init();
    //var w_height = windowHeight();
    w_height = windowHeight();
    w_width=windowWidth();
    if (w_height > 590){
        w_height = 570;
    }
    if (w_width>1024){
        w_width=1024;   
    }
    
    var w_height_T3 = w_height - 300;

    document.getElementById("lblFrom").innerHTML = dispFrom[langMod];
    document.getElementById("lblTo").innerHTML =  dispTo[langMod];  
    document.getElementById("lblDistrictFrom").innerHTML = dispDistricts[langMod];
    document.getElementById("lblDistrictTo").innerHTML = dispDistricts[langMod];
    document.getElementById("lblKeywordsFrom").innerHTML = dispKeywords[langMod];
    document.getElementById("lblKeywordsTo").innerHTML = dispKeywords[langMod];
    document.getElementById("lblShortType1").innerHTML = dispShort1[langMod];
    document.getElementById("lblShortType2").innerHTML = dispShort2[langMod];
    //document.getElementById("lblShortType3").innerHTML = dispShort3[langMod];
    document.getElementById("lblShortType4").innerHTML = dispShort4[langMod];
    //document.getElementById("lblTips").innerHTML = dispTips[langMod];
    //document.getElementById("lblDesc1").innerHTML = dispDesc1[langMod];
    document.getElementById("lblDesc1").innerHTML = getTips();
    document.getElementById("lblToolbar").innerHTML = dispToolbar[langMod];
    document.getElementById("lblLink").innerHTML = dispLink[langMod];   
    document.getElementById("lblClaim").innerHTML = dispClaim[langMod];
    document.getElementById("lblContact").innerHTML = dispContact[langMod];
    document.getElementById("lblHelp").innerHTML = dispHelp[langMod];
    // Added By Henry on 20100101
    document.getElementById("lblToolbar2").innerHTML = dispToolbar2[langMod];
    document.getElementById("lblHelp2").innerHTML = dispHelp2[langMod];
    var str;
    str = '<div id="roadSearchMainDiv">';
    str = str + '<table width="100%" border="0" cellspacing="0" cellpadding="0"><tr>';
    str = str + '<td width="8" height="10"><img src="images/spacer.gif" alt="" width="8" height="10" border="0"></td>';
    str = str + '<td height="10" background="images/table_top_bg.gif"><img src="images/spacer.gif" alt="" width="8" height="10" border="0"></td>';
    str = str + '<td width="5" height="10" bgcolor="#FFFFFF"><img src="images/spacer.gif" alt="" width="5" height="10" border="0"></td>';
    str = str + '</tr></table>';
    str = str + '<table width="100%" border="0" cellspacing="0" cellpadding="0"><tr>';
    str = str + '<td width="13"><img src="images/spacer.gif" alt="" width="13" height="13" border="0" ></td>';
    //str = str + '<td><span class="normalText">' + dispTips[langMod] + ':</span><br><br>';
    //str = str + '<span class="normalText">' + dispDesc1[langMod] + '</span>';
    str = str + '<td><span class="normalText">' + getTips() + '</span>';
    str = str + '</td><td width="5"><img src="images/spacer.gif" alt="" width="5" height="10" border="0">';
    str = str + '</td></tr></table></div>';
    TabHtml_1 = str;
    gBack = str;
    
    str = '<table width="100%" border="0" cellspacing="0" cellpadding="0"><tr>';
    str = str + '<td width="13" rowspan="4"><img src="images/spacer.gif" alt="" width="13" height="10" border="0" /></td>';
    str = str + '<td width="50%" height="5"><img src="images/spacer.gif" alt="" width="5" height="5" border="0" /></td>';
    str = str + '<td width="5" height="5"><img src="images/spacer.gif" alt="" width="5" height="5" border="0" /></td>';
    str = str + '<td width="50%" height="5"><img src="images/spacer.gif" alt="" width="5" height="5" border="0" /></td>';
    str = str + '<td width="5" rowspan="12"><img src="images/spacer.gif" alt="" width="5" height="10" border="0" /></td>';
    str = str + '</tr><tr>'
    str = str + genCategoryButtom(1,dispCategoryButtom1[langMod]);
  str = str + '<td width="5">&nbsp;</td>';
    str = str + genCategoryButtom(2,dispCategoryButtom2[langMod]);
  str = str + '</tr><tr>';
  str = str + '<td width="50%" height="5"><img src="images/spacer.gif" alt="" width="5" height="5" border="0" /></td>';
  str = str + '<td width="5" height="5"><img src="images/spacer.gif" alt="" width="5" height="5" border="0" /></td>';
  str = str + '<td width="50%" height="5"><img src="images/spacer.gif" alt="" width="5" height="5" border="0" /></td>';
  str = str + '</tr><tr>';
  str = str + genCategoryButtom(3,dispCategoryButtom3[langMod]);
    str = str + '<td width="5">&nbsp;</td>';
    str = str + genCategoryButtom(4,dispCategoryButtom4[langMod]);
    str = str + '</tr><tr>';
    str = str + '<td rowspan="6">&nbsp;</td>';
    str = str + '<td width="50%" height="5"><img src="images/spacer.gif" alt="" width="5" height="5" border="0" /></td>';
    str = str + '<td width="5" height="5"><img src="images/spacer.gif" alt="" width="5" height="5" border="0" /></td>';
    str = str + '<td width="50%" height="5"><img src="images/spacer.gif" alt="" width="5" height="5" border="0" /></td>';
    str = str + '</tr><tr>';
  str = str + genCategoryButtom(5,dispCategoryButtom5[langMod]);
    str = str + '<td>&nbsp;</td>';
  str = str + genCategoryButtom(6,dispCategoryButtom6[langMod]);
    str = str + '</tr><tr>';
    str = str + '<td width="50%" height="10"><img src="images/spacer.gif" alt="" width="10" height="10" border="0" /></td>';
  str = str + '<td width="5" height="5"><img src="images/spacer.gif" alt="" width="5" height="5" border="0" /></td>';
  str = str + '<td width="50%" height="10"><img src="images/spacer.gif" alt="" width="10" height="10" border="0" /></td>';
  str = str + '</tr></table>';
    str = str + '<table width="100%" border="0" cellspacing="0" cellpadding="0"><tr>';
  str = str + '<td width="13"><img src="images/spacer.gif" alt="" width="13" height="13" border="0" /></td>';
  str = str + '<td><span class="normalText">' + dispDescription[langMod] + ':</span><br /><br />';
  str = str + '<span class="normalText">' + dispDesc2[langMod] + '</span></td>';
  str = str + '<td width="5"><img src="images/spacer.gif" alt="" width="5" height="10" border="0" /></td>';
  str = str + '</tr></table>';
    TabHtml_2 = str;
    
    //tourism
    str = '<div id="tourismMainDiv" style="height: ' + w_height_T3  + 'px; width: 100%; overflow-x: hidden; overflow-y: auto;">';
    str = str + '<table width="100%" border="0" cellspacing="0" cellpadding="0"><tr>';
    str = str + '<td width="8" height="10"><img src="images/spacer.gif" alt="" width="8" height="10" border="0" /></td>';
    str = str + '<td width="1173" height="10" background="images/table_top_bg.gif"><img src="images/spacer.gif" alt="" width="8" height="10" border="0" /></td>';
    str = str + '<td width="5" height="10" bgcolor="#FFFFFF"><img src="images/spacer.gif" alt="" width="5" height="10" border="0" /></td>';
    
    for(var i=0; i < arrTourism.length; i++){
        var mName = "s3_content_" + arrTourism[i];
        var mDisp = arrTourismD[langMod][i];
        var mSub = "div" + arrTourism[i] + "_";
        
        //alert ('<div id="' + mSub + '"0 style=" margin-right: 1px; display:inline;"></div>');
        str = str + '</tr></table><table width="100%" border="0" cellpadding="0" cellspacing="0" id="from">';
        str = str + '<tr><td width="13" valign="top"><img src="images/spacer.gif" alt="" width="13" height="13" border="0" /></td>';
        str = str + '<td><span class="normalText"><strong class="normalPointText">' + mDisp + '</strong><br /></span> ';
        str = str + '<div id="' + mName + '">';
        str = str + '<div id="' + mSub + '0" style=" margin-right: 1px; display:inline;"></div><div id="' + mSub + '1" style=" margin-right: 1px; display:inline;"></div><div id="' + mSub + '2" style=" margin-right: 1px; display:inline;"></div><div id="' + mSub + '3" style=" margin-right: 1px; display:inline;"></div><div id="' + mSub + '4" style=" margin-right: 1px; display:inline;"></div><div id="' + mSub + '5" style=" margin-right: 1px; display:inline;"></div>';
        str = str + '<div id="' + mSub + '6" style=" margin-right: 1px; display:inline;"></div><div id="' + mSub + '7" style=" margin-right: 1px; display:inline;"></div><div id="' + mSub + '8" style=" margin-right: 1px; display:inline;"></div><div id="' + mSub + '9" style=" margin-right: 1px; display:inline;"></div><div id="' + mSub + '10" style=" margin-right: 1px; display:inline;"></div></div>';
        str = str + '</td><td width="5"><img src="images/spacer.gif" alt="" width="5" height="10" border="0" /></td>';
        str = str + '</tr></table><table width="100%" border="0" cellpadding="0" cellspacing="0" id="tableclose">';
        str = str + '<tr><td height="4" colspan="3"><img src="images/spacer.gif" alt="" width="8" height="4" border="0" /></td>';
        str = str + '</tr><tr><td width="8" height="10"><img src="images/spacer.gif" alt="" width="8" height="10" border="0" /></td>';
        str = str + '<td height="10" background="images/table_top_bg.gif"><img src="images/spacer.gif" alt="" width="8" height="10" border="0" /></td>';
        str = str + '<td width="5" height="10"><img src="images/spacer.gif" alt="" width="5" height="10" border="0" /></td>';
    }
    str = str + '</tr></table></div>';
    TabHtml_3 = str;
    
    e("from").value="";
    e("to").value="";
    handleResize();
    map_init();
    //smMap_init();

    // Henry
    // Remarked on 4 Aug 2011 no pop-up for entering the website
    //OpenChildWindow('welcome.php?lang='+lang, '', 200, 200, 650, 150, false);


    //OpenChildWindow('Survey/' + lang + '/index.html','',0,0,670,570,false);

}

function getTips() {
    var strTips;
    var w_height_FT=(w_height - 270);
    strTips = '<div id="tips" style="height: ' + w_height_FT + 'px; width: 100%; overflow-x: hidden; overflow-y: auto;">';
    strTips = strTips + '  <TABLE width="100%" border="0" cellspacing="0" cellpadding="0">';
    strTips = strTips + '  <TR VALIGN="top">';
    strTips = strTips + '   <TD class="normalText" colspan="2"><b><U>' + dispTips[langMod] + ':</U></b></TD>';
    strTips = strTips + '  </TR>';
    strTips = strTips + '  <TR valign="top">';
    strTips = strTips + '   <TD class="normalText">1.&nbsp;</TD>';
    strTips = strTips + '   <TD class="normalText">' + dispTips1[langMod] + '<A HREF="' + imageFolder + '/pdf/item1.pdf" target="_blank"><IMG style="vertical-align:bottom" SRC="' + imageFolder + '/acrobat.gif" WIDTH="15" HEIGHT="15" BORDER="0" ALT=""></A></TD>';
    strTips = strTips + '  </TR>';
    strTips = strTips + '  <TR VALIGN="top">';
    strTips = strTips + '   <TD class="normalText">2.&nbsp;</TD>';
    strTips = strTips + '   <TD class="normalText">' + dispTips2[langMod] + '<A HREF="' + imageFolder + '/pdf/item2.pdf" target="_blank"><IMG style="vertical-align:bottom" SRC="' + imageFolder + '/acrobat.gif" WIDTH="15" HEIGHT="15" BORDER="0" ALT=""></A></TD>';
    strTips = strTips + '  </TR>';
    strTips = strTips + '  <TR VALIGN="top">';
    strTips = strTips + '   <TD class="normalText">3.&nbsp;</TD>';
    strTips = strTips + '   <TD class="normalText">' + dispTips3[langMod] + '<A HREF="' + imageFolder + '/pdf/item3.pdf" target="_blank"><IMG style="vertical-align:bottom" SRC="' + imageFolder + '/acrobat.gif" WIDTH="15" HEIGHT="15" BORDER="0" ALT=""></A></TD>';
    strTips = strTips + '  </TR>';
    strTips = strTips + '  <TR VALIGN="top">';
    strTips = strTips + '   <TD class="normalText">4.&nbsp;</TD>';
    strTips = strTips + '   <TD class="normalText">' + dispTips4[langMod] + '</TD>';
    strTips = strTips + '  </TR>';
    strTips = strTips + '  <TR VALIGN="top">';
    strTips = strTips + '   <TD class="normalText">5.&nbsp;</TD>';
    strTips = strTips + '   <TD class="normalText">' + dispTips5[langMod] + '</TD>';
    strTips = strTips + '  </TR>';
    strTips = strTips + '  <TR VALIGN="top">';
    strTips = strTips + '   <TD class="normalText">6.&nbsp;</TD>';
    strTips = strTips + '   <TD class="normalText">' + dispTips6[langMod] + '</TD>';
    strTips = strTips + '  </TR>';
    strTips = strTips + '  <TR VALIGN="top">';
    strTips = strTips + '   <TD class="normalText">7.&nbsp;</TD>';
    strTips = strTips + '   <TD class="normalText">' + dispTips7[langMod] + '<A HREF="' + imageFolder + '/pdf/item7.pdf" target="_blank"><IMG style="vertical-align:bottom" SRC="' + imageFolder + '/acrobat.gif" WIDTH="15" HEIGHT="15" BORDER="0" ALT=""></A></TD>';
    strTips = strTips + '  </TR>';
    strTips = strTips + '  <TR VALIGN="top">';
    strTips = strTips + '   <TD class="normalText">8.&nbsp;</TD>';
    strTips = strTips + '   <TD class="normalText">' + dispTips8[langMod].replace('Guide', '<A HREF="' + imageFolder + '/pdf/item8.pdf" target="_blank"><IMG style="vertical-align:bottom" SRC="' + imageFolder + '/acrobat.gif" WIDTH="15" HEIGHT="15" BORDER="0" ALT=""></A>') + '</TD>';
    strTips = strTips + '  </TR>';
    strTips = strTips + '  <TR VALIGN="top">';
    strTips = strTips + '   <TD class="normalText">9.&nbsp;</TD>';
    strTips = strTips + '   <TD class="normalText">' + dispTips9[langMod].replace('Guide', '<A HREF="' + imageFolder + '/pdf/item9.pdf" target="_blank"><IMG style="vertical-align:bottom" SRC="' + imageFolder + '/acrobat.gif" WIDTH="15" HEIGHT="15" BORDER="0" ALT=""></A>') + '</TD>';
    strTips = strTips + '  </TR>';
    strTips = strTips + '  <TR VALIGN="top">';
    strTips = strTips + '   <TD class="normalText">10.&nbsp;</TD>';
    strTips = strTips + '   <TD class="normalText">' + dispTips10[langMod] + '</TD>';
    strTips = strTips + '  </TR>';
    strTips = strTips + '  <TR VALIGN="top">';
    strTips = strTips + '   <TD class="normalText" colspan="2">&nbsp;</TD>';
    strTips = strTips + '  </TR>';
    strTips = strTips + '  <TR VALIGN="top">';
    strTips = strTips + '   <TD class="normalText" colspan="2"><b><U>' + dispNotes[langMod] + ':</U></b></TD>';
    strTips = strTips + '  </TR>';
    strTips = strTips + '  <TR VALIGN="top">';
    strTips = strTips + '   <TD class="normalText">1.&nbsp;</TD>';
    strTips = strTips + '   <TD class="normalText">' + dispNotes1[langMod] + '</TD>';
    strTips = strTips + '  </TR>';
    strTips = strTips + '  <TR VALIGN="top">';
    strTips = strTips + '   <TD class="normalText">2.&nbsp;</TD>';
    strTips = strTips + '   <TD class="normalText">' + dispNotes2[langMod] + '</TD>';
    strTips = strTips + '  </TR>';
    strTips = strTips + '  <TR VALIGN="top">';
    strTips = strTips + '   <TD class="normalText">3.&nbsp;</TD>';
    strTips = strTips + '   <TD class="normalText">' + dispNotes3[langMod] + '</TD>';
    strTips = strTips + '  </TR>';
    strTips = strTips + '  <TR VALIGN="top">';
    strTips = strTips + '   <TD class="normalText">4.&nbsp;</TD>';
    strTips = strTips + '   <TD class="normalText">' + dispNotes4[langMod] + '</TD>';
    strTips = strTips + '  </TR>';
    strTips = strTips + '  <TR VALIGN="top">';
    strTips = strTips + '   <TD class="normalText">5.&nbsp;</TD>';
    strTips = strTips + '   <TD class="normalText">' + dispNotes5[langMod] + '</TD>';
    strTips = strTips + '  </TR>';
    strTips = strTips + '  </TABLE></div>';
    return strTips;
}

function getBrng(lon1, lat1, lon2, lat2) {
  lat1 = lat1 * Math.PI / 180; 
  lat2 = lat2 * Math.PI / 180;
  var dLon = (lon2-lon1) * Math.PI / 180;

  var y = Math.sin(dLon) * Math.cos(lat2);
  var x = Math.cos(lat1)*Math.sin(lat2) - Math.sin(lat1)*Math.cos(lat2)*Math.cos(dLon);
  return ((Math.atan2(y, x) * 180 / Math.PI) + 360) % 360 - 180;
}

function getDistanceByLnglat (lng1,lat1,lng2,lat2)
{
    var radLat1 = getRad(lat1);
    var radLat2 = getRad(lat2);
    var a = radLat1 - radLat2;
    var b = getRad(lng1) - getRad(lng2);
    var s = 2 * Math.asin(Math.sqrt(Math.pow(Math.sin(a / 2), 2) + Math.cos(radLat1) * Math.cos(radLat2) * Math.pow(Math.sin(b / 2), 2)));
    s = s * 6378137.0;
    s = Math.round(s * 10000) / 10000;
    return s;
}

function getRad(d)
{
    return d * Math.PI / 180.0;
} 

//+ Jonas Raoni Soares Silva
//@ http://jsfromhell.com/math/closest-polyline-point [rev. #1]
closestPolyLinePoint = function(px, py, x0, y0, x1, y1, etc, etc, etc){
    function dotLineLength(x, y, x0, y0, x1, y1, o){
        function lineLength(x, y, x0, y0){
            return Math.sqrt((x -= x0) * x + (y -= y0) * y);
        }
        if(o && !(o = function(x, y, x0, y0, x1, y1){
            if(!(x1 - x0)) return {x: x0, y: y};
            else if(!(y1 - y0)) return {x: x, y: y0};
            var left, tg = -1 / ((y1 - y0) / (x1 - x0));
            return {x: left = (x1 * (x * tg - y + y0) + x0 * (x * - tg + y - y1)) / (tg * (x1 - x0) + y0 - y1), y: tg * left - tg * x + y};
        }(x, y, x0, y0, x1, y1), o.x >= Math.min(x0, x1) && o.x <= Math.max(x0, x1) && o.y >= Math.min(y0, y1) && o.y <= Math.max(y0, y1))){
            var l1 = lineLength(x, y, x0, y0), l2 = lineLength(x, y, x1, y1);
            return l1 > l2 ? l2 : l1;
        }
        else {
            var a = y0 - y1, b = x1 - x0, c = x0 * y1 - y0 * x1;
            return Math.abs(a * x + b * y + c) / Math.sqrt(a * a + b * b);
        }
    };
    for(var args = [].slice.call(arguments, 0), lines = []; args.length >= 4; lines[lines.length] = {y1: args.pop(), x1: args.pop(), y0: args.pop(), x0: args.pop()});
    if(!lines.length){
        alert('A');
        return {x: px, y: py};
        }
    for(var l, i = lines.length - 1, o = lines[i],
        lower = {i: i, l: dotLineLength(px, py, o.x0, o.y0, o.x1, o.y1, 1)};
        i--; lower.l > (l = dotLineLength(px, py,
        (o = lines[i]).x0, o.y0, o.x1, o.y1, 1)) && (lower = {i: i, l: l}));
        
    py < Math.min((o = lines[lower.i]).y0, o.y1) ? py = Math.min(o.y0, o.y1)
        : py > Math.max(o.y0, o.y1) && (py = Math.max(o.y0, o.y1));
    px < Math.min(o.x0, o.x1) ? px = Math.min(o.x0, o.x1)
        : px > Math.max(o.x0, o.x1) && (px = Math.max(o.x0, o.x1));
    Math.abs(o.x0 - o.x1) < Math.abs(o.y0 - o.y1) ?
        px = (py * (o.x0 - o.x1) - o.x0 * o.y1 + o.y0 * o.x1) / (o.y0 - o.y1)
        : py = (px * (o.y0 - o.y1) - o.y0 * o.x1 + o.x0 * o.y1) / (o.x0 - o.x1);
    alert('b');
    return {x: px, y: py};
};


function closestPointFromLine(px,py,ax,ay,bx,by){

    var rx = px;
    var ry = py;
    
    if(ax != bx && ay != by){
    
        //alert('normal');
        var s0 = (by-ay)/(bx-ax);
        var s1 = (ax-bx)/(by-ay);
        
        rx = ((s0 * ax) - (s1 * px) + py - ay)/(s0-s1);
        ry = ((s1 * ay) - (s0 * py) + (s1 * s0 * (px-ax)))/(s1-s0);
        
        if(rx <= ax && rx <= bx){
            if(ax <= bx){
                rx = ax;
                ry = ay;
            }
            else{
                rx = bx;
                ry = by;
            }
        }
        else if(rx >= ax && rx >= bx){
            if(ax<=bx){
                rx = bx;
                ry = by;
            }
            else{
                rx = ax;
                ry = ay;
            }
        }
        
    }
    else if(ax == bx){
        
        //alert('same x');
        rx = ax;
        
        if(py <= ay && py <= by){
            ry = Math.min(ay,by);
        }
        else if(py >= ay && py >= by){
            ry = Math.max(ay,by);
        }
        else{
            ry = py;
        }
        
    }
    else if(ay == by){
    
        //alert('same y');
        ry = ay;
        
        if(px <= ax && px <= bx){
            rx = Math.min(ax,bx);
        }
        else if(px >= ax && px >= bx){
            rx = Math.max(ax,bx);
        }
        else{
            rx = px;
        }
        
    }
    
    var dist = twoPointsDistance(px,py,rx,ry);
    
    // alert('line:\n' + px+','+py+'\n'+ax+','+ay+'\n'+bx+','+by+'\n\n'+rx+','+ry);
    return {x:rx, y:ry, d:dist};
    
}

function twoPointsDistance(ax,ay,bx,by){
    return Math.sqrt(((ax-bx) * (ax-bx)) + ((ay-by) * (ay-by)));
}

function closestPointFromPolyLine(pt, line){

    try{
    
        var points_array = new Array();
        
        if(line.length < 2){ return pt; }
        
        for(var i=0; i<line.length-1; i++){
            points_array.push(closestPointFromLine(pt.x,pt.y,line[i].x,line[i].y,line[i+1].x,line[i+1].y));
        }
        
        if(points_array.length < 1){ return pt; }
        if(points_array.length == 1){ return points_array[0]; }
        
        var result_point = {x:points_array[0].x, y:points_array[0].y, d:points_array[0].d };
        
        for(var k=1; k<points_array.length; k++){
        
            if(result_point.d > points_array[k].d){
                result_point.x = points_array[k].x;
                result_point.y = points_array[k].y;
                result_point.d = points_array[k].d;
            }
            
        }
        
        return result_point;
        
    }
    catch(err){
        //alert(err);
        return pt;
    }
    
}

function OnPageUnload(){
    //release supermap
    if( smMap )
    {
        smMap.Destroy();
        smMap = null;
    }
    
    //smMap1.Destroy();
    //smMap1 = null;
    
    //smMap2.Destroy();
    //smMap2 = null;
    
//  smMap3.Destroy();
//  smMap3 = null;
//  
    //smMap4.Destroy();
    //smMap4 = null;

    //DeleteFromDB();

}

var map_idleTimeCount, map_MaxIdleTime;

map_MaxIdleTime=5;
map_idleTimeCount=5;

var theTimer;
var isFocused = false, isMouseOver = false;

function setIsMouseOver(m)
{
    isMouseOver = m;
}

function setIsFocused(m)
{
        //alert(m);
    isFocused = m;
}

function DeleteFromDB()
{
    var http;
    if (window.ActiveXObject)
    {
        http=new ActiveXObject("Microsoft.XMLHTTP");
    }
    else if(typeof XMLHttpRequest != "undefined")
    {
        http=new XMLHttpRequest();
    }
        
    var URL = "logout.php?hash=" + hash + "&ip=" + ip;
    http.open("get", URL);
    http.send(null);    
}

var timerCheckIn;
//Added by Henry
function checkin()
{
    clearTimeout(timerCheckIn); //stop timed refresh login
    var http;
    if (window.ActiveXObject)
    {
        http=new ActiveXObject("Microsoft.XMLHTTP");
    }
    else if(typeof XMLHttpRequest != "undefined")
    {
        http=new XMLHttpRequest();
    }
    

    var URL = "checkin.php?hash=" + hash + "&ip=" + ip;
    http.open("get", URL);
    http.send(null);    
    timerCheckIn = setTimeout("checkin()",15 * 60 * 1000); //set timed refresh login
}
// End by Henry

function Logout()
{
/*
    DeleteFromDB();

    
    //window.open("logoutDrss.html");
    top.location.href = "logoutDrss.php?lang=" + lang;
*/
}

var isFirst = true;
var timerRedirect;

function countdown()
{
    clearTimeout(theTimer);
    if (isMouseOver == false && isFocused == false) 
    {
        map_idleTimeCount--;
    
        if (map_idleTimeCount <= 0 && isFirst == true) 
        {
            isFirst = false;
            Logout();
        }
    }
    else if (isFocused == true || isMouseOver == true)
    {
      map_idleTimeCount = map_MaxIdleTime;
    }
    
    if(isFirst == true)
    {
        theTimer=setTimeout("countdown()", 1000);
    }
}

// Added by Karan
function initRedirect(){
  if (typeof document.body.scrollTop != "undefined"){ //IE,NS7,Moz

    clearTimeout(timerRedirect); //stop timed redirect

    //timerRedirect = setTimeout("Logout()",600000); //set timed redirect
    timerRedirect = setTimeout("Logout()",360 * 60 * 1000); //set timed redirect
    

  }
  else if (typeof window.pageYOffset != "undefined"){ //other browsers that support pageYOffset/pageXOffset instead

    clearTimeout(timerRedirect); //stop timed redirect

    //timerRedirect = setTimeout("Logout()",600000); //set timed redirect
    timerRedirect = setTimeout("Logout()",360 * 60 * 1000); //set timed redirect

  }
  //else do nothing
}

document.onmousemove=initRedirect;
document.onclick=initRedirect;
document.onkeydown=initRedirect;
// End by Karan

window.onresize = handleResize;
window.onload = init;
window.onunload = OnPageUnload;//GUnload;


function timetestcase(){

    var message = '';
    
    //message += 'time1:' + time1 + '\n';
    
    /*
    time2 construct result window
time3 construct result window - complete
time4 prepare routing input
time5 show loading window
time6 prepare send routing request
time7 cancel
time8 sending routing request
time9 sending routing request and clear input - complete
time10 get response raw text
time11 convert text to javascript class - complete
time12 convert text to supermap class - complete
time13 start prepare result (text and map)
time14 start merging and calulating
time15 complete all and hide loading window - complete
    */
    
    message += time2 + ' construct result window' + '\n';
    message += time3 + ' construct result window - complete' + '\n';
    message += time4 + ' prepare routing input' + '\n';
    message += time5 + ' show loading window' + '\n';
    message += time6 + ' prepare send routing request' + '\n';
    //message += time7 + ' construct result window';
    message += time8 + ' sending routing request' + '\n';
    message += time9 + ' sending routing request and clear input - complete' + '\n';
    message += time10 + ' get response raw text' + '\n';
    message += time11 + ' convert text to javascript class - complete' + '\n';
    message += time12 + ' convert text to supermap class - complete' + '\n';
    message += time13 + ' start prepare result (text and map)' + '\n';
    message += time14 + ' start merging and calulating' + '\n';
    message += time15 + ' complete all and hide loading window - complete' + '\n';
    
    /*
    message += 'time2:' + time2 + '\n';
    message += 'time3:' + time3 + '\n';
    message += 'time4:' + time4 + '\n';
    message += 'time5:' + time5 + '\n';
    message += 'time6:' + time6 + '\n';
    message += 'time7:' + time7 + '\n';
    message += 'time8:' + time8 + '\n';
    message += 'time9:' + time9 + '\n';
    message += 'time10:' + time10 + '\n';
    message += 'time11:' + time11 + '\n';
    message += 'time12:' + time12 + '\n';
    message += 'time13:' + time13 + '\n';
    message += 'time14:' + time14 + '\n';
    message += 'time15:' + time15 + '\n';
    */
    
    //message = 'time1:' + time1 + '\n';
    //message = 'time1:' + time1 + '\n';
    //message = 'time1:' + time1 + '\n';
    //message = 'time1:' + time1 + '\n';
    //message = 'time1:' + time1 + '\n';

        
        OpenWindowForText(message,'timetest');
}


/*
/*
function OpenWindowForText(msg,index){

    var OpenWindow=window.open("", "window" + index, "height=500, width=500,toolbar=no,menubar=no,scrollbars=yes");
    OpenWindow.document.write("<HEAD><TITLE>Result" + index + "</TITLE></HEAD>");
    OpenWindow.document.write("<BODY BGCOLOR=pink>");
    OpenWindow.document.write("<PRE>" + msg + "</PRE>");
    OpenWindow.document.write("</BODY>");
    OpenWindow.document.write("</HTML>");
    OpenWindow.document.close();
    
}
*/

function displayDomainName(){
    
    var domain_name = window.location.hostname;
    alert(domain_name);
    
}


function redirectToNewDomain(){

    var domain_name = window.location.hostname;
    if( domain_name == 'drss.td.gov.hk' ){
        window.location = 'http://203.194.149.169';
    }
    
}


